两个相同的assertthrows行的行为不同

eqzww0vc  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(263)

在两个测试中,我有以下相同的assertthrows行:

Assertions.assertThrows(HttpServerErrorException.BadGateway.class, (Executable) restTemplate.postForEntity(builder.toUriString(), request, String.class));

其中一个测试通过,另一个测试出现此错误:
java.lang.ClassCasteException:org.springframework.http.responseentity类不能强制转换为org.junit.jupiter.api.function.executable类(org.springframework.http.responseentity和org.junit.jupiter.api.function.executable在加载器“app”的未命名模块中)
有人知道为什么会这样吗?为什么我能够为一个测试而不是另一个测试将responseentity转换为类可执行文件?

oiopk7p5

oiopk7p51#

请尝试这样做:

Assertions.assertThrows(HttpServerErrorException.BadGateway.class, () -> restTemplate.postForEntity(builder.toUriString(), request, String.class));

现在,你要做到: public <T> ResponseEntity<T> postForEntity(...) 返回 ResponseEntity 然后你把它扔给 Executable 接口smth类似:

ResponseEntity<?> responseEntity = new ResponseEtity<>(...);
Executable ex = (Executable) responseEntity; // ClassCastException
``` `Executable` 是一个功能接口,您应该传递lambda参数,即 `Executable` 接口 `assertThrows` 方法。

相关问题