J'ai trouvé le code ci-dessous dans aquí . Tous les stubs sont créés dans @Before
section.
@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");
}
}
Est-ce la bonne approche ? Ne serait-il pas plus judicieux de créer le stub en @Test
elle-même (afin que les stubs liés à ce test puissent être identifiés facilement).