1

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.

stakolee
  • 893
  • 1
  • 7
  • 20

1 Answers1

1

Maybe duplicated.

In your case, to mock extension function you should use mockkStatic:

mockkStatic("org.springframework.security.core.Authentication.YourFileKt")

mockk<Authentication> {
    every { role } returns role
}

ps.: you don't need to use also for mockk, just call with {}:

mockk<SomeType> {
    // any `every` declaration
}
Pedrox
  • 26
  • 3
  • Thanks for the reply. This didn't quite work. Calling mockkStatic ahead of the mockk errored on my end. It looks like it needs to have a slightly different structure in my code. I'll try to work on it some more. – stakolee Jan 26 '22 at 14:24