Why assert in @PactVerification?

Viewed 1423

I don't understand the use of assert in @PactVerification. To me it seams more like a complicated way of saying 1 == 1. For example:

import static org.assertj.core.api.Assertions.assertThat;
public class PactConsumerDrivenContractUnitTest {
    @Rule
    public PactProviderRuleMk2 mockProvider
      = new PactProviderRuleMk2("test_provider", "localhost", 8080, this);
    @Pact(consumer = "test_consumer")
    public RequestResponsePact createPact(PactDslWithProvider builder) {            
        return builder
          .given("test GET ")
          .uponReceiving("GET REQUEST")
          .path("/")
          .method("GET")
          .willRespondWith()
          .body("{\"condition\": true, \"name\": \"tom\"}")
    }
    @Test
    @PactVerification()
    public void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody() {
        //when
        ResponseEntity<String> response
          = new RestTemplate().getForEntity(mockProvider.getUrl(), String.class);
        //then
        assertThat(response.getBody()).contains("condition", "true", "name", "tom");        
    }
}

So first in "createPact" we state

body("{\"condition\": true, \"name\": \"tom\"}")

Then in givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody annotated @PactVerification we do this

assertThat(response.getBody()).contains("condition", "true", "name", "tom");

But why? We just said that! As far as I can see the assertion does not show up in the generated Pact file. It seams to fill no purpose?

In addition to that, I thought that the idea of contract testing was to reduce the need for integration test since they can break for example if test data changes. But here we still depend on test data. If there are no "Tom" in the Provider, then the test will fail. I primarily wanted to test if the contract is broken, not if the test data has changed.

2 Answers

The example given is a contrived one. In real life using Pact, you wouldn't do this. Your PactVerification would invoke a collaboration method/class/thing which is responsible for the external call to the service you are mocking.

So your assertions are then on what the collaborating function is doing.

Eg. A User Service might create an object with certain properties, that you know only are populated by that external call.

Related