在Junit测试类中正确放置存根以进行线索模拟

时间:2017-01-19 05:21:23

标签: java junit wiremock

我从here找到了以下代码。所有存根都在@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方法本身中创建存根会更好(因此可以轻松识别与该测试相关的存根)。

2 个答案:

答案 0 :(得分:2)

“正确”的方法总是值得商榷。

@Before方法中的代码每次都会在每个@Test方法之前运行。

考虑到这一点,您可以选择是将它们留在那里还是将它们移动到每种测试方法。

对于其中之一,我非常重视可读性,并且我同意,因为在测试之间根本不共享这些存根,所以将每个存根放在使用它们的测试中会更具可读性(因此更好)。 / p>

答案 1 :(得分:2)

在编写单元测试时,您总是需要在“通用”最佳实践(例如:“避免代码重复”)和“特定于单元测试”的最佳实践(例如:理想情况下,所需的所有知识)之间取得平衡理解测试方法理想地位于 测试方法中。

从这个意义上讲,合理的方法可能是:

  • 多个测试用例共享的设置可以进入@Before setup()方法
  • 仅由一个测试用例使用的设置...仅进入该测试用例