我正在编写一些正在使用 Maven Failsafe 插件运行的集成测试 (IT)。
简而言之,这些 IT 执行 HTTP 调用并分析 JSON 响应以确保存在某些元素。
当测试失败时,我希望能够看到 HTTP 请求和响应的详细信息( header 、正文等),而不仅仅是断言失败消息。
如果我的测试看起来像这样:
public class FooBarTest {
MyHttpClient httpClient;
@Before
public void setupHttpClient(){
this.httpClient = ...
}
@Test
public void testFooBarBaz(){
Response response = this.httpClient.get("http://some/url");
Assert.assertEquals(200, response.getStatus());
String json = response.getBody();
Assert.assertEquals("baz", evalJsonPath(json, "foo.bar.id"));
}
}
当从命令行(通过 Maven)运行测试时,我希望能够看到断言错误以及请求和响应的详细信息。我认为这需要打印到 System.out/err,但最好通过一些日志系统来完成。
此外,我希望在 surefire/failsafe 生成的测试 TXT 报告文件中提供相同的信息:
-------------------------------------------------------------------------------
Test set: com.sample.FooBarTest
-------------------------------------------------------------------------------
REQUEST: {...}
RESPONSE: {...}
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 3.273 sec <<< FAILURE! - in com.sample.FooBarTest
testFooBarBaz(com.sample.FooBarTest) Time elapsed: 3.27 sec <<< ERROR!
junit.framework.AssertionFailedError: expected:<200> but was:<404>
at junit.framework.Assert.fail(Assert.java:47)
at junit.framework.Assert.failNotEquals(Assert.java:283)
at junit.framework.Assert.assertEquals(Assert.java:64)
at junit.framework.Assert.assertEquals(Assert.java:195)
at junit.framework.Assert.assertEquals(Assert.java:201)
at com.sample.FooBarTest.testFooBarBaz(FooBarTest.java:XX)
最后,相同的详细信息应该以某种方式出现在 XML 报告中,Jenkins 在向下钻取失败的测试页面时也会显示此信息。
如果可能的话,我只关心在测试失败时打印此信息。
我怎样才能做到这一点?我已经开始研究这些选项,但希望能提供更多指导
- 自定义 JUnit 报告器、运行器或监听器
- JUnit @Rules(方法/类规则、ErrorCollector 等)
- 使用一些特殊的记录器
- ...
附言。我不是在寻找一种将此类详细信息简单地写入单独文件的解决方案,因为我认为这样做的含义对用户不太友好。
谢谢!
最佳答案
您可以将 Hamcrest ( Why should I use Hamcrest-Matcher and assertThat() instead of traditional assertXXX()-Methods ) 与自定义 Matcher<Response>
结合使用( how to implement a hamcrest matcher , Is there a simple way to match a field using Hamcrest? )。
在 Matcher
上做一些工作s,这将允许您将测试编写为:
assertThat(response, hasStatus(200));
assertThat(response, hasJsonPathEval("foo.bar.id", eq("baz"));
任何失败都将包括 toString
代表你的response
.
这在功能上等同于:
assertEquals(response.toString(), 200, response.getStatus());
但更清楚地表明您期望 response
以及失败时显示的测试说明。
关于java - JUnit 集成测试应报告 HTTP 请求/响应详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27892119/