我从这里找到了下面的代码。所有存根都是在@Before
部分中创建的。
@Rule
public WireMockRule wireMockRule = new WireMockRule(18089);
private HttpFetcher instance;
@Before
public void init() {
instance = new HttpFetcher();
// all the stubs
stubFor(get(urlEqualTo("/hoge.txt")).willReturn(
aResponse().withStatus(200).withHeader("Content-Type", "text/plain").withBody("hoge")));
stubFor(get(urlEqualTo("/500.txt")).willReturn(
aResponse().withStatus(500).withHeader("Content-Type", "text/plain").withBody("hoge")));
stubFor(get(urlEqualTo("/503.txt")).willReturn(
aResponse().withStatus(503).withHeader("Content-Type", "text/plain").withBody("hoge")));
}
@Test
public void ok() throws Exception {
String actual = instance.fetchAsString("http://localhost:18089/hoge.txt");
String expected = "hoge";
assertThat(actual, is(expected));
}
@Test(expected = HttpResponseException.class)
public void notFound() throws Exception {
instance.fetchAsString("http://localhost:18089/NOT_FOUND");
}
@Test(expected = HttpResponseException.class)
public void internalServerError() throws Exception {
instance.fetchAsString("http://localhost:18089/500.txt");
}
@Test(expected = HttpResponseException.class)
public void serviceUnavailable() throws Exception {
instance.fetchAsString("http://localhost:18089/503.txt");
}
}
那是正确的做法吗。如果我们在方法本身中创建存根会不会更好@Test
(这样与该测试相关的存根可以很容易地识别)。