Pact:解决 PactMismatchesException

Pact: Solving PactMismatchesException

我正在尝试使用 Pact 设置合同测试(目前只有消费者端)。 这是我的代码的样子:

    @Pact(consumer = "Consumer")
    RequestResponsePact apiIsReachablePact(PactDslWithProvider builder) {
        return builder.given("api is reachable")
                .uponReceiving("load api")
                .method("GET")
                .path("/?format=json")
                .willRespondWith()
                .status(200)
                .headers(headers())
                .body(newJsonBody(object -> {
                    object.stringType("ip", "XYZ");
                }).build())
                .toPact();
    }

    @Test
    @PactTestFor(pactMethod = "apiIsReachablePact")
    public void apiIsReachable() throws IOException {

        //Given
        HttpUriRequest request = new HttpGet("https://api.ipify.org");

        //When
        HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);

        //Then
        assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_OK);
    }

我试图让它尽可能简单,但我收到以下错误:

au.com.dius.pact.consumer.PactMismatchesException: The following requests were not received:
    method: GET
    path: /?format=json
    query: {}
    headers: {}
    matchers: MatchingRules(rules={})
    generators: Generators(categories={})
    body: MISSING
    ...

有人可以帮我吗?

Pact 不会拦截您的请求,因此此调用实际上不会与 Pact 模拟服务器对话,因此未收到它的原因 - 它会转到真实的 API:

        HttpUriRequest request = new HttpGet("https://api.ipify.org");

您不会在消费者测试中针对 Pact 中的真实 API 进行测试,而是模拟提供者并使用 Pact Mock 进行测试。然后它将生成一个合同,提供商可以使用该合同来验证您的期望:

应该是:

    @Test
    @PactTestFor(pactMethod = "apiIsReachablePact")
    public void apiIsReachable(MockServer mockServer) throws IOException {

        //Given
        HttpUriRequest request = new HttpGet(mockServer.getUrl());

        //When
        HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);

        //Then
        assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_OK);
    }

查看此 example and this workshop 了解更多信息。