我有一个调用外部API的Spring应用程序(我无法控制这个外部项目及其代码)。我正在我的 Spring 项目中编写集成测试。测试调用这些 API。其中一个 API 对某些输入抛出异常:
在测试中,我捕获的异常为:
Throwable throwable = catchThrowable(() -> TestHelper.createProduct(...));
assertThat(throwable)
.isInstanceOf(CustomException.class)
.hasMessageContaining(PRODUCT_CREATE_ERROR)
.hasCause(null);
我尝试打印 throwable.getMessage()
,这就是它打印的内容:
An internal error occurred: status code: [400], status text: [Bad Request],
headers: [[Transfer-Encoding:"chunked", Content-Type:"application/json; charset=utf-8", Server:"Kestrel", X-Powered-By:"ASP.NET", Date:"Fri, 10 Sep 2017 22:38:37 GMT"]],
body: [{"status":400,"detail":"Cannot create product."}]
我希望能够捕获消息“无法创建产品”,我在上面的消息中看到并使用它来确认返回了此错误消息,例如:
throwable.
.hasMessageContaining(capturedMessage)
有没有办法获取此消息“无法创建产品。”,我在上面的正文详细信息中看到(来自Exception.getMessage)
如果我执行类似以下操作:.hasMessageContaining(“发生内部错误”),它会起作用,但我也希望能够对错误文本“无法创建产品”执行类似的操作。我如何检索该特定文本并表明返回了此错误?
最佳答案
尝试一下hasStackTraceContaining
,应该可以完成这项工作。
关于java - 从 throwable 获取正文详细信息,并断言抛出异常时返回了确切的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58381718/