I'm trying to use Spock and ConfigurationProperties.
But in my unit test, Mocking @ConfigurationProperties not work for me.
@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()
.
.
.
But when I run test with debug mode, JwtProperties's fields never initialized.
JwtProperties in your application is instantiated by spring. Spring will read value in the properties file and then create the instance with the required value.
In your test you don't have any spring context so nothing will create of JwtProperties for you. Furthermore you are mocking it. I think there is no point on mocking this because you just have to create the instance with the value you want.
Just do:
class JwtTokenProviderTest extends Specification {
private JwtProperties jwtProperties = JwtProperties("my-secret", 60, 120)
private AuthDetailsService authDetailsService = GroovyMock(AuthDetailsService)
private JwtTokenProvider jwtTokenProvider = new JwtTokenProvider(authDetailsService, jwtProperties)