0
0
Testing Fundamentalstesting~15 mins

Contract testing basics in Testing Fundamentals - Build an Automation Script

Choose your learning style9 modes available
Verify API contract between consumer and provider
Preconditions (3)
Step 1: Run the consumer test to generate the contract file
Step 2: Publish the contract file to the contract broker or share with provider
Step 3: Run the provider verification test using the contract file
Step 4: Check that the provider response matches the contract expectations
✅ Expected Result: Provider verification test passes confirming the API contract is fulfilled
Automation Requirements - Pact JVM (Java) or Pact JS (JavaScript)
Assertions Needed:
Verify that provider response status code matches contract
Verify that provider response body matches contract schema and values
Verify that provider headers match contract
Best Practices:
Use explicit contract files shared between consumer and provider
Automate contract verification as part of provider CI pipeline
Use clear and stable request/response examples in contract
Fail tests if provider does not meet contract exactly
Automated Solution
Testing Fundamentals
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.

Common Mistakes - 3 Pitfalls
Not setting up provider states before verification
Running provider verification without the correct contract file
Ignoring header verification in contract tests
Bonus Challenge

Now add data-driven contract tests for multiple user IDs with different expected responses

Show Hint