【问题标题】:Mocking @ConfigurationProperties in Spock with Kotlin not work使用 Kotlin 在 Spock 中模拟 @ConfigurationProperties 不起作用
【发布时间】:2022-01-22 08:07:29
【问题描述】:

我正在尝试使用 Spock 和 ConfigurationProperties。
但在我的单元测试中,模拟 @ConfigurationProperties 对我不起作用。

属性类

@ConfigurationProperties(prefix = "jwt")
@ConstructorBinding
class JwtProperties(
    val secretKey: String,
    val accessTokenExp: Long,
    val refreshTokenExp: Long
) {

    companion object {
        const val TOKEN_PREFIX = "Bearer "
        const val TOKEN_HEADER_NAME = "Authorization"
        const val ACCESS_VALUE = "access"
        const val REFRESH_VALUE = "refresh"
    }
}

测试类

class JwtTokenProviderTest extends Specification {

    private JwtProperties jwtProperties = GroovyMock(JwtProperties)
    private AuthDetailsService authDetailsService = GroovyMock(AuthDetailsService)
    private JwtTokenProvider jwtTokenProvider = new JwtTokenProvider(authDetailsService, jwtProperties)

    def "AuthenticateUser Success"() {
        given:
        jwtProperties.getSecretKey() >> "asdfdsaf"
        jwtProperties.getAccessTokenExp() >> 100000
        def bearerToken = jwtTokenProvider.getAccessToken("email").accessToken
        def accessToken = jwtTokenProvider.parseToken(bearerToken)
        authDetailsService.loadUserByUsername("email") >> new AuthDetails(new User())

        when:
        jwtTokenProvider.authenticateUser(accessToken)

        then:
        noExceptionThrown()
        .
        .
        .

但是当我以调试模式运行测试时,JwtProperties 的字段从未初始化。

【问题讨论】:

    标签: spring-boot kotlin spock configurationproperties


    【解决方案1】:

    应用程序中的 JwtProperties 由 spring 实例化。 Spring 将读取属性文件中的值,然后创建具有所需值的实例。

    在您的测试中,您没有任何弹簧上下文,因此不会为您创建 JwtProperties。此外,您正在嘲笑它。我认为模拟这个没有意义,因为你只需要创建具有你想要的值的实例。

    只要做:

    class JwtTokenProviderTest extends Specification {
    
        private JwtProperties jwtProperties = JwtProperties("my-secret", 60, 120)
        private AuthDetailsService authDetailsService = GroovyMock(AuthDetailsService)
        private JwtTokenProvider jwtTokenProvider = new JwtTokenProvider(authDetailsService, jwtProperties)
    
    

    【讨论】:

      猜你喜欢
      • 2016-12-11
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      • 1970-01-01
      • 2016-04-17
      • 1970-01-01
      • 2019-11-30
      • 1970-01-01
      相关资源
      最近更新 更多