WireMock 测试用例在调用 undefined 时总是失败

WireMock testcases always fail when calling an undefined

我重新编辑了这个问题,因为它可能对其他人有帮助。

我尝试习惯使用 Wiremock 测试客户端以对抗 mocket http 端点。

非常简单的测试场景包括

非存根端点的情况本身是成功的,但似乎使用的 WireMockRule 检查了不匹配调用的列表,并在列表不为空时抛出错误。

测试在早期版本的 Wiremock (1.43) 中运行没有错误,实际上我在 2.21 版本中尝试过。

测试 class 看起来像这样:

public class HttpFetcherTest {

    @Rule
    public WireMockRule wireMockRule = new WireMockRule(18089);

    @Before
    public void init() {
        // only one endpoint is mocked
        stubFor(get(urlEqualTo("/aBody.txt")).willReturn(
                aResponse().withStatus(200).withHeader("Content-Type", "text/plain").withBody("aBody")));
    }

    /**
     * Test calls a defined endpoint. Runs smoothly.
     * @throws Exception
     */
    @Test
    public void found() throws Exception {
        //call the mocked endpoint
        String result  = Request.Get("http://localhost:18089/aBody.txt").execute().returnContent().asString();
        // we expect the mocked return value from the stub
        assertTrue("aBody".equals(result));
    }


    /**
     * The test calls an endpoint that is undefined. Expected behaviour is: a HttpResponseException 
     * is thrown. This is successful but the test fails anyway as the list of unmatched matches in WireMockRule is inspected
     * and the unmatched call is found and interpreted as an error.
     * This means: test fails although it is successful.
     * 
     * This was not an issue in earlier versions of Wiremock - it runs perfectly in 1.43.
     * @throws Exception
     */
    @Test(expected = HttpResponseException.class)
    public void notFound() throws Exception {
        // call an endpoint that is not mocked - we expect a HttpResponseException
        String result  = Request.Get("http://localhost:18089/NOT_FOUND").execute().returnContent().asString();
    }


}

我很纳闷.... 谢谢,石户

在查看 WireMock 资源后,我找到了答案。

可以使用不同的构造函数关闭对不匹配调用列表的检查:

替换行

@Rule
    public WireMockRule wireMockRule = new WireMockRule(18089);

来自

@Rule
    public WireMockRule wireMockRule = new WireMockRule(options().port(18089), false);

解决问题。 谢谢!