当我使用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()
}
我们是否必须添加额外的编码才能删除在这里抛出的类强制转换异常
本部分
given:
authentication.getCredentials() == "Token"
看起来不对。就我所见,比较given:
块中的两个值对你没有帮助:
- 如果
authentication
是mock,它将只返回null
,因此比较将产生false
,但不会做任何有意义的事情 - 如果
authentication
是间谍,它将返回原始方法结果,比较结果将取决于此
我想您可能已经尝试过截断该方法的结果。为此,您需要像在中一样使用>>
given:
authentication.getCredentials() >> "Token"