java - Mockk - 模拟实现多个接口(interface)的最终类​​时出现 ClassCastException

标签 java spring spring-security kotlin mockk

我正在尝试使用这个 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)
    }
}

有什么想法可以解决这个问题吗?

最佳答案

这里的问题是模板参数类型被删除并且无法恢复。唯一的解决方案是直接指定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()

关于java - Mockk - 模拟实现多个接口(interface)的最终类​​时出现 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54073139/

相关文章:

java - Spring jdbc模板内存泄漏在非常基本的应用程序中

spring - 服务器返回 HTTP 响应代码 : 400 using Spring-Security AuthenticationProvider

Grails 中的 Spring Oauth2 提供程序 - 依赖项

java - 为什么 android logcat 不显示运行时异常的堆栈跟踪?

java - 根据环境变量或属性执行切入点

java - Java 小程序可以打开 "select directory"并通过 JavaScript 交互写入文件系统吗?

spring - 在 Groovy/Gradle 构建中使用 JPA 复合键时,Spock 测试失败

java - Spring @Scheduler 执行了两次。我正在使用 spring security,如果我删除上下文参数 spring security 不起作用

java - 在 arrayadapter 中交换数据时从 Binder stub 实现中捕获 RuntimeException

java - 如何设置全屏OnTouchListener?