Verify API contract between consumer and provider
Preconditions (3)
✅ Expected Result: Provider verification test passes confirming the API contract is fulfilled
import au.com.dius.pact.provider.junit5.PactVerificationContext; import au.com.dius.pact.provider.junit5.PactVerificationInvocationContextProvider; import au.com.dius.pact.provider.junit5.Provider; import au.com.dius.pact.provider.junit5.State; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.TestTemplate; import org.junit.jupiter.api.extension.ExtendWith; @Provider("UserService") public class UserServiceProviderTest { @BeforeEach void before(PactVerificationContext context) { context.setTarget(new HttpTestTarget("localhost", 8080)); } @TestTemplate @ExtendWith(PactVerificationInvocationContextProvider.class) void pactVerificationTestTemplate(PactVerificationContext context) { context.verifyInteraction(); } @State("User exists") public void userExists() { // Setup provider state: ensure user data exists in database } @State("User does not exist") public void userDoesNotExist() { // Setup provider state: ensure user data does not exist } }
This code uses the Pact JVM framework to verify the provider API against the contract.
The @Provider annotation names the provider service.
The @BeforeEach method sets the target URL where the provider API runs.
The @TestTemplate method runs all interactions defined in the contract file.
The @State methods set up provider data states required by the contract scenarios.
This structure ensures the provider API responses match the consumer expectations defined in the contract.
Now add data-driven contract tests for multiple user IDs with different expected responses
contract testing in software development?status equal to "success", what will happen if the actual response is {"status": "fail"}?status field to have the value "success" exactly."status": "fail", which does not match the expected value, causing the test to fail.status value does not match -> Option BuserId as a number and active as a boolean. Which contract test scenario best ensures compatibility?userId as a number and active as a boolean, so the contract must enforce these types.{"userId": 123, "active": true} and reject if types differ tests exact types and values, ensuring compatibility. Options A, B, and C ignore or mismatch types, risking integration errors.Pass the test and this pattern moves unknown