JavaSpock:类强制转换异常,但可用于实际调用
当我使用spring boot start进行测试时,我正在测试以下代码工作正常,但在尝试使用spock进行测试时失败。扔
java.lang.ClassCastException: class com.sun.proxy.$Proxy30 cannot be cast to class java.lang.String (com.sun.proxy.$Proxy30 is in unnamed module of loader 'app'; java.lang.String is in module java.base of loader 'bootstrap')
如何解决这个问题。用测试失败的代码和测试更新帖子
测试:
class JWTAuthenticationManagerSpec extends Specification {
private JWTAuthenticationManager sut
private Authentication authentication = Stub()
def 'authenticate throws exception'() {
given:
authentication.getCredentials() == "Token"
when:
sut.authenticate(authentication)
then:
ForbiddenException ex = thrown()
}
}
类方法测试
override fun authenticate(authentication: Authentication): Mono<Authentication> {
//Unit Test Class Cast Exception is being thrown Here
val token = authentication.credentials as String
if (token.isNullOrEmpty()) {
throw ForbiddenException("Invalid access token supplied.")
} else {
log.info { "JWT Token Validation Success" }
}
return Mono.empty()
}
我们是否必须添加额外的代码才能删除这里抛出的类强制转换异常
# 1 楼答案
这部分
看起来不对。就我所见,比较
given:
块中的两个值对您没有帮助:authentication
是一个mock,它将只返回null
,因此比较将产生false
,但不会做任何有意义的事情李>authentication
是间谍,它将返回原始方法结果,比较结果将取决于此李>我想你可能已经试着把这个方法的结果存根了。为此,您希望使用
>>
,如中所示