Skip to content

Commit

Permalink
gh-2: example of a test with mocked dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
pmhsfelix committed Oct 20, 2022
1 parent 2e77425 commit 23b416d
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
1 change: 1 addition & 0 deletions code/tic-tac-tow-service/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ dependencies {
runtimeOnly("io.netty:netty-resolver-dns-native-macos:4.1.82.Final:osx-aarch_64")
}
testImplementation(kotlin("test"))
testImplementation("org.mockito.kotlin:mockito-kotlin:4.0.0")

ktlint("com.pinterest:ktlint:0.47.1")
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package pt.isel.daw.tictactow.service

import org.junit.jupiter.api.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.context.annotation.Bean
import pt.isel.daw.tictactow.domain.PasswordValidationInfo
import pt.isel.daw.tictactow.domain.Token
import pt.isel.daw.tictactow.domain.TokenValidationInfo
import pt.isel.daw.tictactow.domain.User
import pt.isel.daw.tictactow.domain.UserLogic
import pt.isel.daw.tictactow.repository.Transaction
import pt.isel.daw.tictactow.repository.TransactionManager
import pt.isel.daw.tictactow.repository.UsersRepository
import java.time.Instant
import kotlin.test.assertEquals
import kotlin.test.assertNotNull

@SpringBootTest
class SpringBasedServiceTests {

@Autowired
lateinit var usersService: UsersService

@Autowired
lateinit var userLogic: UserLogic

@TestConfiguration
class Config {
@Bean
fun transactionManager(): TransactionManager = object : TransactionManager {
override fun <R> run(block: (Transaction) -> R): R {
val mockedTransaction = mock<Transaction> {
val mockedUsersRepository = mock<UsersRepository> {
on { getTokenByTokenValidationInfo(any()) } doReturn Pair(
User(1, "alice", PasswordValidationInfo("")),
Token(TokenValidationInfo(""), 1, Instant.now(), Instant.now())
)
}

on { usersRepository } doReturn mockedUsersRepository
}

return block(mockedTransaction)
}
}
}

@Test
fun check() {
// given: a valid token
val token = userLogic.generateToken()

// when: getting a user given a token
val user = usersService.getUserByToken(token)

// then: a user is returned
assertNotNull(user)
assertEquals("alice", user.username)
}
}

0 comments on commit 23b416d

Please sign in to comment.