How to verify contract using provider-driven contract test

Reading Time: 3 minutes

this blog will help us to verify the generated contract using a provider-driven contract test.

How does Pact work?

  • The consumer creates the contract file and gives it to the producer. And then the provider side gets verified against the contract.
  • Now let’s explore it more.

Each pact is a collection of integrations. Each interaction describes:

For HTTP:

  • An expected request — describing what the consumer expects to send to the provider.
  • A minimal expected response — describes the part of the response the consumer wants the provider to return.

For messages:

  • The minimal expected message — describing the parts of the message the consumer wants to use.

Verifying the pact in the Pact Broker

Pact Broker webpage for new entry
Pact Broker webpage for Interactions

Implementing pact testing in the system service

  • Start Server for the provider microservice:
mvn liberty:dev
  • After you see the following message, your application server in dev mode is ready:

Create the ProvidertTest class file

  • The connection information for the Pact Broker is provided with the @PactBroker annotation, so dependency also provides a JUnit5 Invocation Context Provider.
  • The pactVerificationTestTemplate() method to generate a test for each of the interactions.
  • The pact.verifier.publishResults property is set  true, So that results are sent to the Pact Broker after the tests are completed.
  • The test target is defined in the PactVerificationContext context to point to the running endpoint of the system microservice.
  • The @State the annotation must match the given() parameter that was provided in the inventory test class, so that Pact can identify which test case to run against which endpoint.
  • The provider has an endpoint “/Key” and “/Version” which returns a user for a request.
@RequestScoped
@Path("/properties")
public class SystemResource {

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  @Timed(name = "getPropertiesTime",
    description = "Time needed to get the JVM system properties")
  @Counted(absolute = true,
    description = "Number of times the JVM system properties are requested")

  public Response getProperties() {
    return Response.ok(System.getProperties()).build();
  }

  @GET
  @Path("/key/{key}")
  @Produces(MediaType.APPLICATION_JSON)
  public Response getPropertiesByKey(@PathParam("key") String key) {
    try {
      JsonArray response = Json.createArrayBuilder()
        .add(Json.createObjectBuilder()
          .add(key, System.getProperties().get(key).toString()))
        .build();
      return Response.ok(response, MediaType.APPLICATION_JSON).build();
    } catch (java.lang.NullPointerException exception) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
  }

  @GET
  @Path("/version")
  @Produces(MediaType.APPLICATION_JSON)
  public JsonObject getVersion() {
    JsonObject response = Json.createObjectBuilder()
                              .add("system.properties.version", 1.1)
                              .build();
    return response;
  }
}
  • then we can execute provider test cases using the below code.
@Provider("System")
@Consumer("Inventory")
@PactBroker(
  host = "localhost",
  port = "9292",
  consumerVersionSelectors = {
    @VersionSelector(tag = "open-liberty-pact")
  })
public class SystemBrokerIT {
  @TestTemplate
  @ExtendWith(PactVerificationInvocationContextProvider.class)
  void pactVerificationTestTemplate(PactVerificationContext context) {
    context.verifyInteraction();
  }

  @BeforeAll
  // tag::publish[]
  static void enablePublishingPact() {
    System.setProperty("pact.verifier.publishResults", "true");
  }
  // end::publish[]

  @BeforeEach
  void before(PactVerificationContext context) {
    int port = Integer.parseInt(System.getProperty("http.port"));
    context.setTarget(new HttpTestTarget("localhost", port));
  }

  // tag::state[]
  @State("wlp.server.name is defaultServer")
  // end::state[]
  public void validServerName() {
  }

  @State("Default directory is true")
  public void validEdition() {
  }

  @State("version is 1.1")
  public void validVersion() {
  }

  @State("invalid property")
  public void invalidProperty() {
  }
}
Pact Broker webpage for verified
  • Generated Pact (Created by Consumer microservice) was successfully verified by the provider microservice through the pact broker.
  • And then the provider side gets verified against the contract.

Techhub

https://github.com/knoldus/pact.io

Reference

https://docs.pact.io/


Knoldus-blog-footer-image

Written by 

Prajjawal is a QA Consultant having experience of more than 1.4 year. He is familiar with core concepts of manual & automation testing using tools like Contract test, Selenium, and Postman Also having knowledge of Core Java, Python and Data Science. He is always eager to learn new and advanced concepts in order to improve himself. He likes to watch web series and play cricket.

Leave a Reply