My code is extending Spring Boot's Authentication class with properties derived from the JWT. For example:
import org.springframework.security.core.Authentication
...
val Authentication.role: List<String>?
get() = (principal as? Jwt)?.let {
if (it.containsClaim("test/role/claim")) {
it.getClaimAsStringList("test/role/claim")
} else {
null
}
}
This works in the code just fine but I'm stuck on how to test it with mockk.
In this example, "role" won't get hit at all
fun mockAuthenticationWithAuthorities(
userId: String,
authorities: Collection<Authorities> = emptyList(),
principal: Any? = null,
role: List<String>? = null,
) =
mockk<Authentication>().also {
every { it.name } returns userId
every { it.authorities } returns authorities.map { SimpleGrantedAuthority(it.value) }
every { it.principal } returns principal
every { it.role } returns role
}
Based on some of the answers here I tried this variation:
fun mockAuthenticationWithAuthorities(
userId: String,
authorities: Collection<Authorities> = emptyList(),
principal: Any? = null,
role: List<String>? = null,
) =
mockk<Authentication>().also {
every { it.name } returns userId
every { it.authorities } returns authorities.map { SimpleGrantedAuthority(it.value) }
every { it.principal } returns principal
every { it getProperty "role" } returns role
}
But it fails with io.mockk.MockKException: can't find property role for dynamic property get
Any ideas how to properly test this case?
Thanks.