Skip to content

Instantly share code, notes, and snippets.

@krishnanunnijs
Created April 30, 2024 17:47
Show Gist options
  • Save krishnanunnijs/54dbe6cc0e95b4123b5c5697af50bebd to your computer and use it in GitHub Desktop.
Save krishnanunnijs/54dbe6cc0e95b4123b5c5697af50bebd to your computer and use it in GitHub Desktop.
Contract Test using PACT
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.consumer.junit5.PactConsumerTestExt;
import au.com.dius.pact.consumer.junit5.PactTestFor;
import au.com.dius.pact.core.model.RequestResponsePact;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import java.util.HashMap;
import java.util.Map;
@ExtendWith(PactConsumerTestExt.class)
public class ApiContractTest {
@PactTestFor(providerName = "ProviderService", hostInterface = "localhost", port = "8080")
public class PactConsumerTest {
@Pact(consumer = "ConsumerService")
public RequestResponsePact createPact(PactDslWithProvider builder) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return builder
.given("Test State")
.uponReceiving("A request to /api/data")
.path("/api/data")
.method("GET")
.willRespondWith()
.status(200)
.headers(headers)
.body("{\"name\":\"test\",\"status\":\"success\"}")
.toPact();
}
@Test
@PactTestFor(pactMethod = "createPact")
void testConsumerService() {
// Here you would use an HTTP client to make the request to the provider API
// and verify the response matches the expected results defined in the pact
}
}
}
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.consumer.junit5.PactConsumerTestExt;
import au.com.dius.pact.consumer.junit5.PactTestFor;
import au.com.dius.pact.core.model.RequestResponsePact;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import java.util.HashMap;
import java.util.Map;
@ExtendWith(PactConsumerTestExt.class)
public class GenericApiContractTest {
// Utility class for creating PACT contracts
static class PactContractGenerator {
static RequestResponsePact createContract(String providerName, String interactionDescription,
String requestPath, String requestMethod,
int expectedStatus, String responseBody) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return PactDslWithProvider
.consumer("ConsumerService")
.given("Test State")
.uponReceiving(interactionDescription)
.path(requestPath)
.method(requestMethod)
.willRespondWith()
.status(expectedStatus)
.headers(headers)
.body(responseBody)
.toPact();
}
}
@PactTestFor(providerName = "ProviderService", hostInterface = "localhost", port = "8080")
public class PactConsumerTest {
@Pact(consumer = "ConsumerService")
public RequestResponsePact createPact() {
// Example usage of the utility class
return PactContractGenerator.createContract("ProviderService",
"A request to /api/data", "/api/data", "GET",
200, "{\"name\":\"test\",\"status\":\"success\"}");
}
@Test
@PactTestFor(pactMethod = "createPact")
void testConsumerService() {
// Implement your HTTP request and response verification here
}
}
}
@krishnanunnijs
Copy link
Author

krishnanunnijs commented Aug 28, 2024

import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.consumer.junit5.PactConsumerTestExt;
import au.com.dius.pact.consumer.junit5.PactTestFor;
import au.com.dius.pact.core.model.RequestResponsePact;
import org.junit.jupiter.api.extension.ExtendWith;
import static io.restassured.RestAssured.given;

@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "UserProvider")
public class UserConsumerTest {

    @Pact(consumer = "UserConsumer")
    public RequestResponsePact createPact(PactDslWithProvider builder) {
        return builder
                .given("User exists")
                .uponReceiving("A request for user")
                .path("/users/1")
                .method("GET")
                .willRespondWith()
                .status(200)
                .body("{\"id\": 1, \"name\": \"John Doe\"}")
                .toPact();

// Create a Pact contract based on the extracted information
      /*  return pactBuilder
            .given("a valid user")
            .uponReceiving("a GET request to /users")
            .with(Matchers.method("GET"), Matchers.path("/users"))
            .willRespondWith(Matchers.status(200))
            .toBody(Matchers.like(new User(1, "John Doe")))
            .build(); */

/*
 return builder
            .given("A specific state")
            .uponReceiving("A request for some endpoint")
            .path(openAPI.getPaths().get("/your-endpoint").getGet().getOperationId())
            .method("GET")
            .willRespondWith()
            .status(200)
            .body("{}") // This can be dynamically generated based on your OpenAPI spec
            .toPact();
*/
    }

    @Test
    void testGetUser(MockServer mockServer) {
        given()
            .baseUri(mockServer.getUrl())
        .when()
            .get("/users/1")
        .then()
            .statusCode(200)
            .body("name", equalTo("John Doe"));
    }
}

@krishnanunnijs
Copy link
Author

import au.com.dius.pact.provider.junit5.PactVerificationContext;
import au.com.dius.pact.provider.junit5.PactVerificationInvocationContextProvider;
import au.com.dius.pact.provider.junit5.PactVerifyProvider;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;

@ExtendWith(PactVerificationInvocationContextProvider.class)
public class UserProviderTest {

    @TestTemplate
    @ExtendWith(PactVerificationInvocationContextProvider.class)
    void pactVerificationTestTemplate(PactVerificationContext context) {
        context.verifyInteraction();
    }

    @PactVerifyProvider("A request for user")
    public String verifyGetUser() {
        return "{\"id\": 1, \"name\": \"John Doe\"}";
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment