1

I have to do a POC on contract testing using pact, but I couldn't found anything helpful for a newbie. Can someone help me with the working code, how to install, execute I will be grateful.

norbitrial
  • 14,716
  • 7
  • 32
  • 59
  • I've written these articles in case they may be of any use? https://hmh.engineering/how-to-write-and-validate-pact-contracts-using-junit5-and-restassured-72b578e7dd65 https://hmh.engineering/pact-with-java-by-example-bb7175f62d58 – Francislainy Campos Apr 15 '21 at 08:44

1 Answers1

1

I tried to explain below.

Consumer: Contract created by consumer.

Provider: Contracts tested by provider.

Pack Broker: After contracts are created under location (like targer/pacts) defined by you, you must publish the contracts to the common platform where consumer and provider will see.

Consumer side - Create contract for provider

public class CreateContractForProvider {
@Rule //Provider, HostInterface and Port defined with @Rule annotation (Used PactProviderRuleMk2)

public PactProviderRuleMk2 pactProviderRuleMk2 = new PactProviderRuleMk2(
        // Provider Application Name
        "ProviderName",

        //Mock Server
        "localhost",
        8112,

        this);

@Pact(consumer = "ConsumerName") // Consumer Application Name (Our application) - Consumer defined with @Pact annotation(

public RequestResponsePact createPact(PactDslWithProvider builder) {

    Map<String, String> headers = new HashMap();
    headers.put("Content-Type", "application/json"); //Defined headers


    //Defined responses with PactDslJsonBody()
    DslPart expectedResultBodyWhenGetPayments = new PactDslJsonBody()
            .integerType("id",308545)
            .integerType("contractNo",854452)
            .numberType("amount",3312.5)
            .stringType("status","UNPAID")
            .asBody();


    return builder
            .uponReceiving("A request for all payments")
            .path("/payments")
            .method("GET")
            .willRespondWith()
            .status(200)
            .headers(headers)
            .body(expectedResultBodyWhenGetPayments).toPact(); //Response bodyies and headers used in return builder
  //  We can define more than one endpoint with .uponReceiving or .given



 //Then we have to test beacuse contracts are created test stage. 
 //When we say test with  @PactVerification, the server we described above stands up(localhost:8112). İf we get localhost:8112/(definedpathlike/payments) its return expectedResultBodyWhenGetPayments.If the test is successful, the contracts is create.
 @Test
 @PactVerification()
public void pactVerification() {    

    int contractNo=((Integer) new   ContractTestUtil(pactProviderRuleMk2.getPort()).getContractResponse("/payments","contractNo")).intValue();
    assertTrue(contractNo == 854452);
}}

Test Util

public class ContractTestUtil {

int port=8111;

   public ContractTestUtil(int port) {
    this.port=port;
    System.out.println("Custom port "+port);
}

public  Object getContractResponse(String path,String object) {
    try {
        System.setProperty("pact.rootDir", "./target/pacts");
        System.setProperty("pact.rootDir", "./target/pacts");

        String url=String.format("Http://localhost:%d"+path, port);
        System.out.println("using url: "+url);
        HttpResponse httpResponse = Request.Get(url).execute().returnResponse();
        String json = EntityUtils.toString(httpResponse.getEntity());
        System.out.println("json="+json);
        JSONObject jsonObject = new JSONObject(json);
        return jsonObject.get(object);
    }
    catch (Exception e) {
        System.out.println("Unable to get object="+e);
        return null;
    }
}}

Define Pact Broker

The PactBrokerUr lmust be defined before publishing in pom.

            <plugin>
            <!-- mvn pact:publish  -->
            <groupId>au.com.dius</groupId>
            <artifactId>pact-jvm-provider-maven_2.11</artifactId>
            <version>3.5.10</version>
            <configuration>
                <pactDirectory>./target/pacts</pactDirectory> <!-- Defaults to ${project.build.directory}/pacts -->
                <pactBrokerUrl>http://yourmachine:8113</pactBrokerUrl>
                <projectVersion>1.1</projectVersion> <!-- Defaults to ${project.version} -->
                <trimSnapshot>true</trimSnapshot> <!-- Defaults to false -->
            </configuration>
        </plugin>

Now, we can publish with pact:puplish command.

Provider Side - Call contracts created by consumer

In this stage you can test with failsafe plugin. Beacuse its integraion test.

@RunWith(PactRunner.class) // Say JUnit to run tests with custom Runner
@Provider("ProviderName")
@Consumer("ConsumerName")// Set up name of tested provider// Provider Application Name
@PactBroker(port = "8113", host = "yourmachine")
public class VerifyContractsWhichCreatedForProviderIT {

private static ConfigurableWebApplicationContext configurableWebApplicationContext;

@BeforeClass
public static void start() {
    configurableWebApplicationContext = (ConfigurableWebApplicationContext)
      SpringApplication.run(Application.class);
}

@TestTarget // Annotation denotes Target that will be used for tests
public final Target target = new HttpTarget(8080); //Test Target
}

Finally,you can create contrats and verify contrast created for you with clean test pact:publish verify command.

IlGala
  • 3,331
  • 4
  • 35
  • 49
MhmtMelek
  • 11
  • 2
  • do u have code in gitrepo, it will be a great help for beginners like me – abhishek singh Oct 16 '19 at 04:40
  • Hi, I added the project , you can create and publish contracts.You need to install the Pact Broker first.https://github.com/Mehmetmelekk/Contract_Test_With_Pact_Framework.git – MhmtMelek Oct 16 '19 at 11:16