Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

Design a test strategy for a Spring Boot order service that talks to PostgreSQL, Kafka and two HTTP APIs.

I would layer it by what each part can break. Domain logic, such as pricing and order state rules, gets plain unit tests with no Spring context. Controllers get @WebMvcTest slice tests, and repositories get @DataJpaTest against PostgreSQL in Testcontainers with the real migrations. Kafka producers and listeners get integration tests with a Kafka container. The two HTTP clients are tested against WireMock and kept honest with contract tests. On top, a small number of end-to-end tests run in a deployed environment for the critical flows, such as placing and paying for an order.

Why this question is asked

An order service is a good design exercise because it has a bit of everything: business rules, a REST API, a relational database, asynchronous messaging and two downstream HTTP dependencies. A strategy that treats all of it the same way will be either slow or blind. Interviewers ask this question to see whether we can match each kind of risk with the cheapest test that catches it, and whether we can explain the choices rather than list tools. In this answer, we will sketch the service, then design each layer of tests, the domain, the web and persistence slices, Kafka, the HTTP clients and the end-to-end tests, and finish with how the pieces run in the pipeline.

1The Service and Where Its Risks Live

Picture the service. A REST API accepts orders, the domain applies pricing, discounts and state rules (an order moves from NEW to PAID to SHIPPED and can be cancelled only before shipping), and orders are stored in PostgreSQL. When an order is placed, the service publishes an OrderPlaced event to Kafka, and it listens for PaymentCompleted events from the payment service. It calls two HTTP APIs: a customer service to check the customer, and a stock service to reserve items.

Each part can break in its own way. Rules can be wrong for certain inputs; the API can map requests or errors wrongly; SQL and mappings can fail on the real database; messages can be serialised wrongly or processed twice; HTTP calls can use the wrong path or fail badly under timeouts; and the whole flow can fail when deployed. The strategy gives each of these risks a home.

Test layers for the order service
RiskTest typeToolsTypical speed
Pricing and state rulesUnit tests, no SpringJUnit, AssertJMilliseconds
Request mapping, validation, errorsWeb slice@WebMvcTest, MockMvcTesterAbout a second per context
SQL, mappings, migrationsJPA slice on real PostgreSQL@DataJpaTest, Testcontainers, FlywaySeconds, shared container
Event formats, listener behaviourKafka integration@SpringBootTest, Kafka container, AwaitilitySeconds
HTTP client behaviourClient integrationWireMock, @RestClientTestFast
Agreement with other servicesContract testsPact or Spring Cloud ContractFast, in each pipeline
Whole flow when deployedEnd-to-end smokeREST Assured against a deployed envMinutes, few tests
Each risk gets the cheapest test that can actually catch it.

2Domain Logic: Plain Unit Tests

Business rules should live in plain Java classes that do not depend on Spring, so they can be tested without any context. These tests are where most of the test count lives, because rules have many combinations: discounts for different customer tiers, rounding, state transitions that are allowed or rejected.

Java
class OrderTest {
@Test
void cannotCancelAfterShipping() {
Order order = Order.place(customerId, List.of(line("A1", 2, "19.95")));
order.markPaid(paymentId);
order.markShipped();
assertThatThrownBy(order::cancel).isInstanceOf(IllegalStateException.class); // shipped orders stay shipped
}
@Test
void goldCustomersGetTenPercentOff() {
Money total = pricing.total(List.of(line("A1", 2, "19.95")), Tier.GOLD);
assertThat(total).isEqualTo(Money.eur("35.91")); // 39.90 minus 10 percent
}
}

If these rules can only be tested through a Spring context or a database, that is a design signal: logic is mixed with infrastructure, and pulling it out makes both the code and the tests better.

3Web and Persistence Slices

Controllers get @WebMvcTest tests with the service mocked. They check that requests map correctly, validation rejects bad input with the right error body, domain exceptions become the right status codes, and the JSON field names are what clients expect.

Repositories get @DataJpaTest tests against PostgreSQL in a Testcontainers container, with @AutoConfigureTestDatabase(replace = NONE), Flyway running the real migrations, and ddl-auto set to validate. That checks custom queries, entity mappings, constraints such as a unique order number, and the migrations themselves on the production engine and version. One container is shared across all test classes in the JVM so the cost is paid once.

4Kafka: Integration Tests With a Real Broker

Messaging needs a real broker, because the risks are in serialisation, topic names, consumer configuration and error handling, none of which a mock exercises. A @SpringBootTest with a Kafka container and the PostgreSQL container tests the listener end to end: publish a PaymentCompleted event, then wait for the order to become PAID.

Java
@SpringBootTest
@Testcontainers
class PaymentListenerIT {
@Container @ServiceConnection
static KafkaContainer kafka = new KafkaContainer("apache/kafka:4.0.0"); // check the container class for your version
@Container @ServiceConnection
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17.6");
@Autowired KafkaTemplate<String, String> kafkaTemplate;
@Autowired OrderRepository orders;
@Test
void marksOrderPaidWhenPaymentCompletes() {
Order order = orders.save(anOrder().withStatus(NEW).build()); // unique order for this test
kafkaTemplate.send("payments.completed", order.getId().toString(),
"{\"orderId\":" + order.getId() + ",\"paymentId\":\"p-1\"}");
await().atMost(Duration.ofSeconds(10))
.untilAsserted(() -> assertThat(orders.findById(order.getId()).orElseThrow().getStatus()).isEqualTo(PAID));
}
}

The same setup tests the producer side by consuming from the OrderPlaced topic and checking the message, and it is the right place to test failure handling: a malformed message going to a dead letter topic, or a duplicate PaymentCompleted event being ignored because the listener is idempotent. Awaitility replaces sleeps, and unique ids per test keep the tests independent.

5HTTP Clients: WireMock Plus Contracts

The customer and stock clients are tested against WireMock started on a dynamic port, with the base URLs set through @DynamicPropertySource. These tests check paths, headers, JSON mapping, error mapping such as a 404 becoming CustomerNotFound, and resilience: timeouts with withFixedDelay, retries with scenarios, and the fallback when the stock service is down. Services that use these clients are unit tested with the client interface mocked.

Hand-written stubs can drift from the real APIs, so the stubs are backed by consumer-driven contract tests with Pact or Spring Cloud Contract. The order service publishes what it expects from the customer and stock services, those services verify it in their own pipelines, and the same applies to the Kafka events, where the payment service's PaymentCompleted format and our OrderPlaced format are covered by messaging contracts.

6End-to-End Tests and the Pipeline

Finally, a small number of end-to-end tests run against a deployed environment with the real customer, stock and payment services: place an order, pay for it, see it marked paid, and cancel an unpaid order. Perhaps five to ten tests, run after deployment to a test environment, checking the real wiring, configuration and security between services. They are deliberately few, because everything they check in detail is already covered lower down.

In the pipeline, unit and slice tests run first and give feedback within a couple of minutes. Kafka and client integration tests and contract verification run next, still on the build agent with containers. The end-to-end smoke tests run after deployment and gate promotion to production. Test duration and flakiness are tracked per stage so the shape stays healthy.

7Follow-up questions

Would you use embedded Kafka instead of a Kafka container?

Spring Kafka's embedded broker is faster to start and fine for simple tests, but a Kafka container runs the same broker image and version as production and avoids classpath clashes between the broker and client libraries. I would use the container for the listener and producer integration tests, and shared across classes, the start-up difference is small.

How do you test the transactional outbox, if the service uses one?

With the PostgreSQL and Kafka containers together: place an order, check that the order row and the outbox row were written in the same transaction, then wait with Awaitility for the event to appear on the topic. A second test makes the publisher fail and checks that the event is published later rather than lost.

Where do performance tests fit?

Separately from this functional strategy. Load tests against a production-like environment, run on a schedule or before major releases, check throughput and latency. They do not belong in the per-commit pipeline, but their results should feed back into the design, for example adding an index found missing under load.

8Conclusion

In this answer, we designed a test strategy for an order service by matching each risk to the cheapest test that catches it. Domain rules get plain unit tests, controllers get @WebMvcTest slices, and repositories get @DataJpaTest against PostgreSQL in Testcontainers with real migrations. Kafka listeners and producers are tested with a real Kafka container and Awaitility, HTTP clients against WireMock with contract tests keeping the stubs honest, and a handful of end-to-end tests check the critical flows in a deployed environment. The pipeline runs the fast layers first and tracks duration and flakiness per stage.

What to say in the interviewAbout 90 seconds aloud

Open with

I'd organise it by risk. The domain logic, pricing, discounts and the order state machine, lives in plain Java and gets plain unit tests with no Spring context, which is where most tests are, because rules have many combinations.

Then, if they want more

The REST API gets @WebMvcTest tests with the service mocked, checking mapping, validation, error bodies and status codes. Repositories get @DataJpaTest against PostgreSQL in Testcontainers, same major version as production, with Flyway running the real migrations and ddl-auto on validate, and one shared container per JVM.

For Kafka, I'd write @SpringBootTest integration tests with a Kafka container: publish a PaymentCompleted event and use Awaitility to wait until the order is PAID, plus tests for the OrderPlaced producer, a malformed message going to the dead letter topic and duplicates being ignored.

The two HTTP clients get tests against WireMock on a dynamic port, covering paths, headers, JSON, 404 mapping, timeouts and retries. Since hand-written stubs drift, I'd add consumer-driven contract tests with Pact or Spring Cloud Contract for both HTTP APIs and the Kafka events, verified in the providers' pipelines.

On top, maybe five to ten end-to-end tests in a deployed environment for critical flows like place, pay and cancel. The pipeline runs unit and slice tests first for fast feedback, then container-based tests and contract verification, and the end-to-end smoke tests after deployment.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Design a test strategy for a Spring Boot order service that talks to PostgreSQL, Kafka...": https://scrivio-interview-library.netlify.app/java/test-strategy/2776d5b77e/