调用未定义时,WireMock测试用例总是失败

问题描述 投票:1回答:1

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

我尝试习惯使用Wiremock测试客户端对mocket http-endpoints的影响。

非常简单的测试场景包括

  • 一个调用存根端点的测试用例(效果很好)
  • 调用非存根端点的测试用例(失败)

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

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

测试类看起来像这样:

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();
    }


}

我很困惑....谢谢,Ishiido

java wiremock
1个回答
0
投票

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

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

替换线

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

通过

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

解决了这个问题。谢谢!

© www.soinside.com 2019 - 2024. All rights reserved.