【问题标题】:two identical assertThrows lines behave differently两条相同的 assertThrows 行表现不同
【发布时间】:2021-07-09 08:53:58
【问题描述】:

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

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

一个测试通过,另一个给出这个错误:

java.lang.ClassCastException:类 org.springframework.http.ResponseEntity 不能转换为类 org.junit.jupiter.api.function.Executable(org.springframework.http.ResponseEntity 和 org.junit.jupiter.api. function.Executable 位于加载程序“app”的未命名模块中)

有谁知道为什么会这样?为什么我能够将 ResponseEntity 强制转换为一个测试而不是另一个测试的类 Executable?

【问题讨论】:

  • 你能添加一个调试评估的屏幕截图吗?你试图在这两种情况下投射什么?我觉得测试通过正在返回 null,这可以解释为什么你能够投射它

标签: java class exception junit5


【解决方案1】:

请尝试一下:

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

现在你做到了: public <T> ResponseEntity<T> postForEntity(...) 返回ResponseEntity 然后你把它转换成Executable interface smth like:

ResponseEntity<?> responseEntity = new ResponseEtity<>(...);
Executable ex = (Executable) responseEntity; // ClassCastException

Executable是一个函数式接口,你应该传递lambda参数,即在assertThrows方法中实现Executable接口。

【讨论】:

  • 这个问题已经以另一种方式进行了排序,因为另一个类导致请求对象不包含正确的内容,但是这些信息对我理解事物非常有价值,并且可能在以后有用。谢谢你们!
  • 在任何情况下,您都不应该在那里进行转换,而是使用 lambda。您将Executable 转换为ResponseEntity,尽管ResponseEntity 及其超类都没有实现此接口。您在一种测试方法中编写代码仅因为您的 postForEntity(...) 方法返回 null
猜你喜欢
  • 1970-01-01
  • 2017-12-10
  • 1970-01-01
  • 1970-01-01
  • 2016-05-12
  • 2015-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多