3

我从这里找到了下面的代码。所有存根都是在@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(这样与该测试相关的存根可以很容易地识别)。

4

2 回答 2

2

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

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

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

一方面,我非常重视可读性,并且我同意由于这些存根在测试之间根本不共享,因此将每个存根放入使用它们的测试中会更具可读性(因此更好)。

于 2017-01-19T06:24:52.467 回答
2

在编写单元测试时,您总是需要在“通用”最佳实践(例如:“避免代码重复”)和“单元测试特定”最佳实践(例如:理想情况下,理解一个测试方法最好位于测试方法中)。

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

  • 多个测试用例共享的设置可以进入 @Before setup() 方法
  • 仅由一个测试用例使用的设置...仅用于该测试用例
于 2017-01-19T12:29:32.363 回答