Java 在wiremock的Junit测试类中正确放置存根
我从中找到以下代码。所有存根都是在Java 在wiremock的Junit测试类中正确放置存根,java,junit,wiremock,Java,Junit,Wiremock,我从中找到以下代码。所有存根都是在@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.tx
@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
方法本身中创建存根(这样就可以很容易地识别与该测试相关的存根)不是更好吗
@Before方法中的代码将在每次@Test方法之前运行
记住这一点,您可以选择是将它们留在那里,还是将它们移动到每个测试方法中
一、 首先,对可读性的评价非常高,我同意,因为这些存根在测试之间根本不共享,所以将每个存根放在使用它们的测试中会更具可读性(从而更好)。在编写单元测试时,您始终需要在“通用”最佳实践之间取得平衡(例如:“无论如何避免代码重复”)以及“特定于单元测试”的最佳实践(例如:理想情况下,理解测试方法所需的所有知识都位于该测试方法中) 从这个意义上讲,一个合理的方法可以是:
- 多个测试用例共享的设置可以进入@Before setup()方法
- 仅由一个测试用例使用的设置。。。只进入那个测试用例