我正在编写一些正在使用Maven Failsafe插件运行的集成测试(IT)。
简而言之,这些IT执行HTTP调用并分析JSON响应,以确保存在某些元素。
当测试失败时,我希望能够看到HTTP请求和响应的详细信息(标头,正文等),而不仅仅是断言失败消息。
如果我的测试看起来像这样:
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,但是最好通过一些Logging系统来完成。
另外,我希望可以在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等)
使用一些特殊的记录器
...
PS。我不是在寻找一种将这些详细信息简单地写到单独文件中的解决方案,因为我认为这样做的含义对用户不太友好。
谢谢!
最佳答案
您可以将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
上做一些工作,这将使您可以将测试编写为:
assertThat(response, hasStatus(200));
assertThat(response, hasJsonPathEval("foo.bar.id", eq("baz"));
并且任何失败将包括您的
toString
的response
表示形式。在功能上等效于:
assertEquals(response.toString(), 200, response.getStatus());
但可以更清楚地表明您希望在失败时显示
response
和测试说明。