我正在努力创建一个简单的 stub 。我一直在网上关注wiremock教程,但在我面临的问题上没有成功。特别是,AssertMethod 中的“Get”方法给我带来了很多问题。不知道怎么解决。
public class WeatherApplicationTest {
@Rule
public WireMockRule wireMockRule = new WireMockRule();
public WireMockServer wireMockServer = new WireMockServer(); //No-args constructor will start on port 8080, no HTTPS
@BeforeClass
public void setUpClass() {
wireMockServer.start();
}
@AfterClass
public void tearDownClass() {
wireMockServer.stop();
}
@Test
public void statusMessage() throws IOException{
wireMockRule.stubFor(get(urlEqualTo("/some/thing"))
.willReturn(aResponse()
.withStatus(200)
.withStatusMessage("Everything is fine")
.withHeader("Content-Type", "Text/Plain")));
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://localhost:" + wireMockServer.port() + "/some/thing");
HttpResponse response = client.execute(request);
assertThat(response.GET("/some/thing").statusCode(), is(200));
}
}
我在以下行中收到错误:
assertThat(response.GET("/some/thing").statusCode(), is(200));
GET 方法用红色下划线表示。
请帮忙!
最佳答案
WireMock documentation并没有很好地概述如何与之联系(但是,在他们的辩护中,这并不真正属于他们的份额)。
正如我在评论中回避的那样,HttpResponse
不包含 GET()
方法,这就是为什么你会得到“红色下划线”(即:错误)。
所以我们知道我们正在寻找针对状态代码的断言。如果我们看一下 Javadoc在 HttpResponse
类中,有一个 StatusLine
类,可以从 HttpResponse
的 getStatusLine()
中检索,并且Javadoc该类显示它包含一个 getStatusCode() 方法。将此信息合并到您的答案中,断言需要更新为:
assertThat(response.getStatusLine().getStatusCode(), is(200));
此外,正如 Tom 在评论中指出的那样,删除 WireMockServer
(以及 start/stop
和 getPort()
> 调用;您可以从规则中获取端口。并且应该静态调用 stubFor(...)
方法(而不是作为规则的一部分)。
关于java - WireMock: stub - 无法正确实现 "AssertThat"方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50000848/