1

I'm trying to use a mock of this Java class:

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

So I've created a mock like so:

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

in order to test this bit of Java code:

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

and I'm getting the following error when I try and use it

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

Test class here:

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

Any ideas how to fix this ?

4

1 回答 1

2

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

val mockk = mockk<HttpSecurity>(relaxed = true)
val csrf = mockk.csrf()
every { csrf.disable() } returns mockk(relaxed = true)
val disable = csrf.disable()
disable.headers()
于 2019-01-26T08:47:47.447 回答