簡體   English   中英

Mockk - 模擬實現多個接口的最終類​​時出現 ClassCastException

[英]Mockk - ClassCastException when mocking final class that implements multiple interfaces

我正在嘗試使用這個 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)
    }
}

任何想法如何解決這一問題 ?

這里的問題是模板參數類型被刪除並且無法恢復。 唯一的解決方案是直接指定模擬,以便reified類型將捕獲實際類:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM