kotlin春季测试-如何访问实现存储库passwordEncoder的服务?

时间:2020-04-07 04:51:29

标签: spring-boot kotlin junit mockk

我目前正在制作一个简单的基于Kotlin的Spring Boot Web项目。 我想做的是测试一些控制器,并设法使用了模拟。

但是在这个项目中,我没有使控制器能够处理帐户,因此我必须手动运行AccountService。但是它是由AccountRepository(Interface)和passwordEncoder实现的。所以当我尝试做

@Autowired lateinit var accountService: AccountService(AccountRepository, PasswordEncoder)

它根本不起作用。 (我还尝试将AccountRepository更改为@Autowired lateinit var accountRepository:AccountRepository,但是无法构造接口)

所以我尝试的是

@TestConfiguration
class BoardGetControllerTest {
    @Bean
    fun service() = mockk<AccountService>()
}
private val boardGetControllerTest = BoardGetControllerTest()

这是我的测试

object TestD : Spek({

  describe("A set") {
    context("is empty") {
        var result = "0"
        var expected = "404 NOT_FOUND"

        val user = Account(null,
                "User1",
                "password",
                mutableSetOf(AccountRole.ADMIN, AccountRole.USER),
                LocalDateTime.now())
        boardGetControllerTest.service().createAccount(user)
        it("adds 2 to 2") {
            assertEquals(expected, result)
        }
    }
  }

})

这是我的accountService

@Service
class AccountService(@Autowired private val accountRepo: AccountRepository,
                       @Autowired private val passwordEncoder: PasswordEncoder) : 
UserDetailsService {
    fun createAccount(account: Account): Account {
        if (accountRepo.findByUsername(account.username) == null) {
            account.password = this.passwordEncoder.encode(account.password)
            return accountRepo.save(account)
        } else {
            throw AlreadyExistsException("Username Already Exists.")
        }
    }

    override fun loadUserByUsername(username: String?): UserDetails {
        return username?.let { accountRepo.findByUsername(it)?.getAuthorities() }
                ?: throw UsernameNotFoundException("$username cannot found")
    }
}

感谢帮助。

0 个答案:

没有答案