Skip to content
javahacks.dev
Testing

How to Do Contract Testing With Pact in Java Services

Do contract testing with Pact in Java: consumer tests that generate a contract, provider verification, the Pact Broker, can-i-deploy and CI workflow.

6 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the OpenJDK, JUnit5, Jenkins and Selenium logos.

Two services agree on an interface in a meeting, and from then on each team tests against its own memory of it. The consumer mocks the provider's response by hand, the provider changes a field name, and both test suites stay green until the integration environment fails. Pact removes the hand-written mock. The consumer's test records what it needs from the provider as a contract file, and the provider replays that file against its real API. Neither test needs the other service running, yet a mismatch fails a build. This post sets up the flow with Pact JVM and JUnit 5, covers the broker and the can-i-deploy check that gates releases, and says what a contract should and should not contain. It uses Pact JVM 4.6 and JDK 25.

The flow

Pact is consumer-driven. The sequence is five steps. The consumer team writes a test that describes a request and the response it expects. Running the test against a mock server generates a pact file in JSON. The pact is published to a broker. The provider's build fetches the pacts of its consumers and replays each request against the real application, checking that the response matches the expectation. The result is published back, so the broker knows which versions of provider and consumer are compatible.

The consumer defines only what it uses. A provider response with twenty fields satisfies a contract that mentions three, and the other seventeen can change freely. That is the property that distinguishes this from a full API schema.

Consumer test

src/test/java/com/example/billing/OrdersClientPactTest.javajava
@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "orders-service", pactVersion = PactSpecVersion.V4)
class OrdersClientPactTest {

    @Pact(consumer = "billing-service")
    V4Pact orderExists(PactDslWithProvider builder) {
        return builder
            .given("order 42 exists")
            .uponReceiving("a request for order 42")
                .path("/orders/42")
                .method("GET")
            .willRespondWith()
                .status(200)
                .headers(Map.of("Content-Type", "application/json"))
                .body(new PactDslJsonBody()
                    .integerType("id", 42)
                    .stringMatcher("status", "PLACED|SHIPPED", "PLACED")
                    .decimalType("total", 19.90))
            .toPact(V4Pact.class);
    }

    @Test
    void reads_an_order(MockServer server) {
        var client = new OrdersClient(server.getUrl());

        Order order = client.find(42L);

        assertEquals("PLACED", order.status());
    }
}

The method annotated @Pact describes the interaction. given("order 42 exists") names a provider state: a precondition the provider must set up before replaying the request. The body uses matchers (integerType, decimalType, stringMatcher), not literal values, so the contract says "an integer", not "exactly 42 and nothing else". Literals would couple the provider to your test data. The test then runs the real client against Pact's mock server, which serves the described response. If the client sends a different path or method, the mock server rejects the call and the test fails, so the contract is also a check on the client.

On success, Pact writes target/pacts/billing-service-orders-service.json. Commit nothing from target/; publish it from CI.

Provider verification

src/test/java/com/example/orders/OrdersProviderPactTest.javajava
@Provider("orders-service")
@PactBroker(url = "https://pact-broker.example.com")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class OrdersProviderPactTest {

    @LocalServerPort int port;
    @MockitoBean OrderService orders;

    @BeforeEach
    void target(PactVerificationContext context) {
        context.setTarget(new HttpTestTarget("localhost", port));
    }

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

    @State("order 42 exists")
    void order42() {
        when(orders.find(42L)).thenReturn(new Order(42L, "PLACED", new BigDecimal("19.90")));
    }
}

The @PactBroker annotation tells the verifier where to fetch the pacts of every consumer of orders-service. A @TestTemplate runs once per interaction, each replayed against the running application on a random port. The @State method sets up the precondition named in the contract; here it stubs the service layer, which keeps the test fast and focused on the HTTP contract. If a consumer asks for a state that has no @State method, the verification fails with a message naming it, which is how a provider learns what its consumers assume. The stubbing approach is described in replacing beans in Spring tests.

Set pact.verifier.publishResults=true in CI, so the broker learns the outcome. Without it, the broker has contracts and no verification record, and can-i-deploy has nothing to base a decision on.

The broker and can-i-deploy

A Pact Broker (open source, or the hosted PactFlow) stores pacts, versions and verification results. Its most useful feature is the compatibility matrix and the command that reads it:

Shell
pact-broker can-i-deploy --pacticipant billing-service --version "$GIT_SHA" --to-environment production

The command answers yes only if every provider that this version of billing-service depends on has verified it, in the target environment. Run it in the deployment pipeline before releasing either side, and a consumer that needs a field the production provider lacks cannot ship early. After deploying, record it with pact-broker record-deployment. Tag or branch the pacts so that a feature branch is verified against the matching provider branch and not against everything. The workflow and its commands are documented at docs.pact.io.

Where the broker is unavailable, pacts can be shared as files, from a repository or an artifact store. That works for two teams and stops being workable at five.

Where it fits

Contract tests sit between unit tests and end-to-end tests. They replace the end-to-end test that existed to check that two services still understand each other, and they run without a deployed environment. They do not check business logic behind the interface, authentication flows, performance or the correctness of the data. A reasonable suite has few of them per integration, and they belong with the other low-level checks in the test pyramid for Java services. For Spring teams who prefer the provider to own the contract, the alternative is Spring Cloud Contract, and the choice between them is covered there.

Good practice

Keep contracts about shape and key behaviour: status codes, the fields the consumer reads, error responses the consumer handles. Do not encode business rules, such as "orders over 100 get a discount"; those belong in the provider's own tests. Use matchers for values and keep literals for fixed identifiers. One pact per consumer-provider pair, with a small number of interactions. Name provider states in the domain's words, and make them cheap to set up. Review pact changes like API changes, since a new interaction is a new demand on the provider. Do not run the provider verification against a shared staging environment; use an isolated instance with stubbed collaborators, or the result depends on the environment's data.

Event contracts

Pact also covers asynchronous messages through the message pact API: the consumer declares the message it can process, and the provider verifies that it produces such a message. This fits events on Kafka or a queue, where the contract is the payload shape. A schema registry with compatibility rules solves the neighbouring problem for Avro and Protobuf, described in schema registries and event versions. Use one or both, depending on whether you want the consumer's needs or the producer's compatibility rules to drive.

When this does not apply

For a public API with unknown consumers, there is no consumer to write a pact; use an OpenAPI description and compatibility checks. When one team owns both services and deploys them together, plain integration tests may be enough. The JVM implementation guide is at docs.pact.io/implementation_guides/jvm.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.