'Kotlin Mockk a getter with parameters

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.



Solution 1:[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
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1