Skip to content
javahacks.dev
Microservices

How to Test Microservices Without Running Everything

Test a Java microservice in isolation: unit and slice tests, Testcontainers for its own database, WireMock for dependencies and contract tests.

6 min read
Summarize in AI
Flat illustration of services connected around a gateway, with the OpenJDK, Istio and Spring Boot logos.

Starting twenty services to test one change is slow, flaky and expensive. The way out is to test each service against its boundaries with fakes whose behaviour is checked, and to keep a thin layer of whole system tests. This uses Spring Boot 4, JUnit and Testcontainers on JDK 25. The general shape is in the test pyramid.

1. Unit tests for the logic

Keep business rules in plain classes that take their dependencies as arguments, and test them with no framework:

java
class PricingTest {
    @Test
    void appliesVolumeDiscount() {
        var pricing = new Pricing(Map.of("A-1", new BigDecimal("10.00")));
        assertThat(pricing.total("A-1", 100)).isEqualByComparingTo("900.00");
    }
}

This is where most tests should live. They run in milliseconds and pinpoint failures. The role of mocks is discussed in test doubles.

2. The service's own database

A service owns its data, so test it against the real database engine in a container:

java
@DataJpaTest
@Testcontainers
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class OrderRepositoryTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:17");

    @Autowired OrderRepository orders;

    @Test
    void findsOpenOrders() { /* save and query */ }
}

@ServiceConnection wires the connection properties. An in-memory substitute database hides differences in SQL and locking. If the container will not start, see could not find a valid Docker environment.

3. Calls to other services

Replace each dependency with a stub server that returns canned responses:

java
@RegisterExtension
static WireMockExtension pricing = WireMockExtension.newInstance()
        .options(wireMockConfig().dynamicPort()).build();

@Test
void fallsBackWhenPricingIsSlow() {
    pricing.stubFor(get(urlPathMatching("/prices/.*"))
            .willReturn(aResponse().withFixedDelay(3000).withStatus(200)));

    var result = client.priceOf("A-1");         // client has a 500 ms timeout
    assertThat(result).isEqualTo(Price.unknown("A-1"));
}

Stubs make failure cases cheap to test: slow responses, 500s, malformed bodies, which the real service rarely produces on demand. These are the behaviours covered in retries, timeouts and bulkheads.

4. Contracts

A stub only reflects what the consumer's author believes. If the provider changes its response, the stub still passes and production breaks. Consumer driven contract tests close this gap:

  • The consumer test records the requests it makes and the responses it needs as a contract.
  • The provider build replays the contract against the real service and fails if it cannot satisfy it.

Pact and Spring Cloud Contract both do this. The contract file is the shared artifact, and no environment with both services is needed. For HTTP APIs published with a specification, validating responses against the OpenAPI document is a lighter form, see contract first development.

5. Messaging

For event consumers, send a message to the test broker container (Kafka via Testcontainers) and assert on the outcome. Test the duplicate delivery case as well, per idempotent consumers.

6. A few end to end tests

Keep a short set that runs against a deployed environment and walks the key journeys: sign up, buy, pay. They catch configuration and wiring problems that no isolated test sees. Keep them few, retry no failures silently, and treat a flaky one as a bug, with the guidance in flaky tests.

A consumer contract, written and verified

The stub in the WireMock test above is a claim the consumer makes about the provider. A contract turns the claim into a file the provider must satisfy. With Pact on the JVM, the consumer test describes one interaction and runs against a mock server that Pact starts, so the consumer's real HTTP client is exercised end to end.

src/test/java/dev/javahacks/orders/PricingClientPactTest.javajava
@ExtendWith(PactConsumerTestExt.class)
@PactTestFor(providerName = "pricing-service")
class PricingClientPactTest {

    @Pact(consumer = "order-service")
    V4Pact priceLookup(PactDslWithProvider builder) {
        return builder
                .given("item A-1 costs 10.00")
                .uponReceiving("a price lookup for A-1")
                .path("/prices/A-1")
                .method("GET")
                .willRespondWith()
                .status(200)
                .headers(Map.of("Content-Type", "application/json"))
                .body(new PactDslJsonBody()
                        .stringValue("sku", "A-1")
                        .decimalType("amount", 10.00))
                .toPact(V4Pact.class);
    }

    @Test
    @PactTestFor(pactMethod = "priceLookup")
    void readsThePrice(MockServer server) {
        var client = new PricingClient(server.getUrl());
        assertThat(client.priceOf("A-1").amount()).isEqualByComparingTo("10.00");
    }
}

Running the test writes target/pacts/order-service-pricing-service.json. The given string is a provider state, a name the provider maps to setup code. decimalType says the consumer cares that amount is a decimal number, not that it equals 10.00, which keeps the contract from failing when test data changes.

The provider side replays it

The provider build loads the pact file, from a folder or from a broker, replays each request against the running service and compares the response with what the consumer needs.

src/test/java/dev/javahacks/pricing/PricingProviderPactTest.javajava
@Provider("pricing-service")
@PactFolder("pacts")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, properties = "server.port=8085")
class PricingProviderPactTest {

    @Autowired PriceRepository prices;

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

    @State("item A-1 costs 10.00")
    void itemA1() {
        prices.save(new Price("A-1", new BigDecimal("10.00")));
    }

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

Rename amount to price in the provider and this test fails with a diff naming the consumer that depends on the field. That failure is the deliverable. It happens in the provider's own pipeline, before the change is deployed, and without starting the order service.

Make the clock and the data belong to the test

Most flaky microservice tests share state or read the wall clock. Inject a Clock into the code under test and fix it in the test, so a discount that ends at midnight does not fail at 23:59.

java
@TestConfiguration
class FixedClockConfig {
    @Bean @Primary
    Clock clock() {
        return Clock.fixed(Instant.parse("2025-03-14T09:00:00Z"), ZoneOffset.UTC);
    }
}

Give each test its own data by generating identifiers (UUID.randomUUID()) instead of reusing order-1. A container can then be shared between test classes, which cuts minutes from the suite, without one class seeing another's rows.

Break the network on purpose

A stub that answers slowly tests your timeout. A proxy between the service and its real dependency tests everything else: connection resets, half-open sockets, packets that arrive late. The Testcontainers Toxiproxy module puts one in front of any container.

java
static Network network = Network.newNetwork();
static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:17").withNetwork(network).withNetworkAliases("db");
static ToxiproxyContainer toxiproxy = new ToxiproxyContainer("ghcr.io/shopify/toxiproxy:2.5.0").withNetwork(network);

@Test
void surfacesAnErrorWhenTheDatabaseIsSlow() throws IOException {
    Proxy proxy = new ToxiproxyClient(toxiproxy.getHost(), toxiproxy.getControlPort())
            .createProxy("db", "0.0.0.0:8666", "db:5432");
    proxy.toxics().latency("slow", ToxicDirection.DOWNSTREAM, 2_000);

    assertThatThrownBy(() -> orders.findOpenOrders())
            .hasRootCauseInstanceOf(java.sql.SQLTimeoutException.class);
}

Point the service's JDBC URL at the proxy port. The test shows whether your query timeout is set at all. Many services find out in this test that it is not.

Decide what runs when

SuiteRunsNeeds
Uniton every save and commitnothing
Slice with containerevery commitDocker
Contract, consumer sideevery commitnothing
Contract, provider sideevery pull request on either sidepact files
End to endafter each deploy to stagingthe deployed environment

The point of the table is the last column. A test that needs the deployed system cannot block a commit, so it must be few and must run where the system exists. Everything above it stays fast enough that nobody skips it.

How many of each, and who owns them

A common failure is a suite shaped like an hourglass: plenty of unit tests, plenty of end to end tests, and nothing in the middle. The middle is where microservice bugs live, in serialisation, in query behaviour, in what a client does when a response has an extra field. A useful rule of thumb is that every outbound call has one consumer contract, every repository method with a non-trivial query has one container test, and every journey the business would phone about has one end to end test. Count those three and compare with what you have.

Ownership matters as much as count. The team that owns the provider owns the provider side verification, and the consumer team owns the pact. A pact file that lives in one repository and is verified by nobody is a document, not a test. Publish pacts to a broker and have the provider pipeline fail when a verification is missing, so a consumer cannot add an expectation that nobody checks. When two teams disagree about a field, the pact is where they argue, in a pull request, before either side deploys.

Where this does not apply

Two services that always change together and share a release may be one service. Splitting them forced all of this ceremony, see microservices versus monolith. References: Testcontainers for Java, WireMock and Pact.

Also inTesting
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.