【问题标题】:Kotlin Mockk a getter with parametersKotlin Mockk 带参数的 getter
【发布时间】:2022-01-26 14:14:05
【问题描述】:

我的代码使用从 JWT 派生的属性扩展 Spring Boot 的 Authentication 类。例如:

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
        }
    }

这在代码中工作得很好,但我坚持如何用 mockk 测试它。

在这个例子中,“角色”根本不会被命中

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
    }

根据这里的一些答案,我尝试了这种变化:

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
    }

但它失败了io.mockk.MockKException: can't find property role for dynamic property get

任何想法如何正确测试这个案例?

谢谢。

【问题讨论】:

    标签: spring kotlin jwt mockk


    【解决方案1】:

    也许是duplicated。

    在您的情况下,要模拟扩展功能,您应该使用mockkStatic:

    mockkStatic("org.springframework.security.core.Authentication.YourFileKt")
    
    mockk<Authentication> {
        every { role } returns role
    }
    

    ps.:你不需要使用also 进行模拟,只需使用{} 调用即可:

    mockk<SomeType> {
        // any `every` declaration
    }
    

    【讨论】:

    • 感谢您的回复。这并不完全奏效。在 mockk 之前调用 mockkStatic 在我这边出错了。看起来它需要在我的代码中具有稍微不同的结构。我会再努力一些。
    猜你喜欢
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 2017-05-21
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多