【问题标题】:Mockk - ClassCastException when mocking final class that implements multiple interfacesMockk - 模拟实现多个接口的最终类​​时发生 ClassCastException
【发布时间】:2019-01-07 11:03:50
【问题描述】:

我正在尝试使用这个 Java 类的模拟:

public final class HttpSecurity extends
        AbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain, HttpSecurity>
        implements SecurityBuilder<DefaultSecurityFilterChain>,
        HttpSecurityBuilder<HttpSecurity>

所以我创建了一个这样的模拟:

private val httpSecurity: HttpSecurity = mockk(relaxed = true)

为了测试这段 Java 代码:

  protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().
                headers().frameOptions().disable().and()
                .formLogin().loginPage("/login").permitAll()....etc

当我尝试使用它时遇到以下错误

java.lang.ClassCastException: org.springframework.security.config.annotation.web.HttpSecurityBuilder$Subclass2 cannot be cast to org.springframework.security.config.annotation.web.builders.HttpSecurity

在这里测试类:

package com.whatever

import io.mockk.mockk
import io.mockk.mockkClass
import org.junit.jupiter.api.Test

import org.springframework.core.env.Environment
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.config.annotation.web.builders.HttpSecurity

internal class SecurityConfigTest {


    private val authManager: AuthenticationManager = mockk()
    val env : Environment = mockk()
    private val httpSecurity: HttpSecurity = mockk(relaxed = true)

    val securityConfig : SecurityConfig = SecurityConfig(authManager,env)

    @Test
    fun configure() {
        securityConfig.configure(httpSecurity)
    }
}

任何想法如何解决这个问题?

【问题讨论】:

  • 似乎mockk 创建了一个类型作为构建器方法的轻松返回值。尝试手动模拟每个方法以从那里返回 HttpSecurity
  • 谢谢,我想我可能不这样做就可以逃脱,但我想不会:-)
  • 添加了一个问题github.com/mockk/mockk/issues/219

标签: java spring spring-security kotlin mockk


【解决方案1】:

这里的问题是模板参数类型被删除并且无法恢复。唯一的解决方案是直接指定 mock 以便 reified 类型将捕获实际类:

val mockk = mockk<HttpSecurity>(relaxed = true)
val csrf = mockk.csrf()
every { csrf.disable() } returns mockk(relaxed = true)
val disable = csrf.disable()
disable.headers()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多