3

I found below code from here. All the stubs are created in @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");
}
}

Is that the correct approach. Wouldn't it be better if we create the stub in @Test method itself (so the stubs related to that test can be identified easily).

prime
  • 14,464
  • 14
  • 99
  • 131

2 Answers2

2

The "correct" approach is always debatable.

The code in the @Before method will run each time, before each @Test method.

With that in mind, you can choose whether to leave them there or move them to each test method.

I, for one, value readability very highly, and I agree that since these stubs aren't shared at all in between tests, putting each stub in the test that uses them would be more readable (and thus better).

Rodrigo
  • 508
  • 4
  • 10
2

When writing unit tests, you always need to balance between "generic" best practices (such as: "avoid code duplication at all means") and the "unit test specific" best practices (such as: ideally, all knowledge required to understand a test method is ideally located within that test method).

In that sense, a reasonable approach could be:

  • settings shared by several test cases could go into a @Before setup() method
  • settings used only by one test case ... go only into that test case
GhostCat
  • 137,827
  • 25
  • 176
  • 248