Java NotesRohit’s interview study guide
Chapter 15

Testing Java and Spring Boot

JUnit, AssertJ and Mockito compared with the Jest you know, then Spring Boot's test support: the full context, test slices, @MockitoBean, controller tests with MockMvcTester and RestTestClient, and a real PostgreSQL in Docker with Testcontainers. Every example was run with Spring Boot 4.2.0 on Java 25 (JUnit Jupiter 6.1.3, AssertJ 3.27.7, Mockito 5.24.0, Testcontainers 2.0.5).

Try it yourself. Every example is the starter project from chapter 11 plus the files shown; tests go under src/test/java. ./mvnw test compiles everything and runs every test class. The Terminal blocks show Maven's summary only, from Results: to BUILD …: the counts, and the details of any test that failed. Passing tests aren't listed by name. The counts always include one test you didn't write: the starter's own ShopApplicationTests.contextLoads, which checks that the application starts. The Testcontainers examples also need Docker running (Docker Desktop, OrbStack, Colima or similar).

8 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#JUnit compared with Jest

Added

JUnit is Java's test framework, and its current generation is called JUnit Jupiter. Spring Boot 4.2 ships JUnit 6.1.3: version 6 (September 2025) raised the minimum to Java 17 and gave the platform and the Jupiter engine one shared version number, but the API you write against, org.junit.jupiter.api, is the same one JUnit 5 had. If you last used JUnit 4 (@RunWith, @Before, public test methods), that's the part that changed: no runners, lifecycle annotations renamed, test classes and methods can be package-private.

The mental model maps almost one to one onto Jest. A test class is a describe block, each @Test method is an it, and @Nested inner classes are nested describes. JUnit creates a new instance of the test class for every test method, so instance fields are fresh each time: that's why a field set in @BeforeEach is safe, and why state can't leak between tests through fields.

Assertions come from a separate library. JUnit has its own (assertEquals(expected, actual)), but Spring's starter includes AssertJ, whose fluent assertThat(actual).isEqualTo(expected) reads like Jest's expect(actual).toBe(expected) and gives far better failure messages. Use AssertJ.

JestJUnit Jupiter + AssertJ
describe("Cart", …)a test class CartTest, @DisplayName("Cart")
nested describea @Nested inner class
it("…", …) / test(…)a @Test method (name it like a sentence)
beforeEach / afterEach@BeforeEach / @AfterEach
beforeAll / afterAll@BeforeAll / @AfterAll (static methods)
expect(x).toBe(y) / toEqual(y)assertThat(x).isEqualTo(y) (uses equals)
expect(list).toEqual([a, b])assertThat(list).containsExactly(a, b)
expect(fn).toThrow("msg")assertThatThrownBy(() -> …).hasMessageContaining("msg")
it.skip / it.only@Disabled / run one test: ./mvnw test -Dtest='CartTest#name'
it.each@ParameterizedTest (next topic)
jest.fn() / jest.mock()Mockito's mock() / Spring's @MockitoBean (below)
src/main/java/com/example/shop/Cart.java
package com.example.shop;

import java.util.ArrayList;
import java.util.List;

public class Cart {
    public record Line(String item, long priceCents, int quantity) {
    }

    private final List<Line> lines = new ArrayList<>();

    public void add(String item, long priceCents, int quantity) {
        if (quantity < 1) {
            throw new IllegalArgumentException("quantity must be at least 1, was " + quantity);
        }
        lines.add(new Line(item, priceCents, quantity));
    }

    public List<String> items() {
        return lines.stream().map(Line::item).toList();
    }

    public long totalCents() {
        return lines.stream().mapToLong(l -> l.priceCents() * l.quantity()).sum();
    }
}
src/test/java/com/example/shop/CartTest.java
package com.example.shop;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

@DisplayName("Cart")
class CartTest {
    private Cart cart;

    @BeforeEach
    void newCart() {
        cart = new Cart();
    }

    @Test
    @DisplayName("is empty when created")
    void emptyAtFirst() {
        assertThat(cart.items()).isEmpty();
        assertThat(cart.totalCents()).isZero();
    }

    @Nested
    @DisplayName("with two lines")
    class WithTwoLines {
        @BeforeEach
        void addLines() {
            cart.add("Keyboard", 4999, 1);
            cart.add("Mouse", 1500, 2);
        }

        @Test
        void listsItemsInOrder() {
            assertThat(cart.items()).containsExactly("Keyboard", "Mouse");
        }

        @Test
        void totalsPriceTimesQuantity() {
            assertThat(cart.totalCents()).isEqualTo(7999);
        }
    }

    @Test
    void rejectsZeroQuantity() {
        assertThatThrownBy(() -> cart.add("Keyboard", 4999, 0))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessageContaining("at least 1");
    }
}
Terminal
$ ./mvnw test
[INFO] Results:
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
What’s happening
  1. CartTest is plain Java: no Spring, no annotations on the class except a display name. Maven's test plugin (Surefire) finds it because its name ends in Test and it's under src/test/java.
  2. Before every test, JUnit creates a new CartTest object and calls newCart(), so each test starts with an empty cart. emptyAtFirst checks items() is empty and the total isZero().
  3. WithTwoLines is a @Nested class: an inner class, so it can see the outer cart field. For its tests JUnit runs the outer @BeforeEach first, then the inner one, exactly like nested beforeEach in Jest. Both tests start with a keyboard and two mice.
  4. containsExactly("Keyboard", "Mouse") checks contents and order; isEqualTo(7999) checks 4999 × 1 + 1500 × 2. assertThatThrownBy runs the lambda, expects it to throw, and then asserts on the exception's type and message.
  5. The summary: Tests run: 5, Failures: 0. That's the four tests in CartTest (two at the top level, two nested) plus the starter's contextLoads.
AdvancedNote: display names and the Maven summary
AdvancedWhat a failing test prints

Here the cart has a bug (it forgets the quantity) and one test expects the wrong order. The summary names each failure and AssertJ explains it:

src/main/java/com/example/shop/Cart.java
package com.example.shop;

import java.util.ArrayList;
import java.util.List;

public class Cart {
    public record Line(String item, long priceCents, int quantity) {
    }

    private final List<Line> lines = new ArrayList<>();

    public void add(String item, long priceCents, int quantity) {
        lines.add(new Line(item, priceCents, quantity));
    }

    public List<String> items() {
        return lines.stream().map(Line::item).toList();
    }

    public long totalCents() {
        return lines.stream().mapToLong(Line::priceCents).sum();
    }
}
src/test/java/com/example/shop/CartTest.java
package com.example.shop;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

class CartTest {
    private Cart cart;

    @BeforeEach
    void addLines() {
        cart = new Cart();
        cart.add("Keyboard", 4999, 1);
        cart.add("Mouse", 1500, 2);
    }

    @Test
    void listsItemsInOrder() {
        assertThat(cart.items()).containsExactly("Mouse", "Keyboard");
    }

    @Test
    void totalsPriceTimesQuantity() {
        assertThat(cart.totalCents()).isEqualTo(7999);
    }
}
Terminal
$ ./mvnw test
[INFO] Results:
[ERROR] Failures: 
[ERROR]   CartTest.listsItemsInOrder:20 
Expecting actual:
  ["Keyboard", "Mouse"]
to contain exactly (and in same order):
  ["Mouse", "Keyboard"]
but there were differences at these indexes:
  - element at index 0: expected "Mouse" but was "Keyboard"
  - element at index 1: expected "Keyboard" but was "Mouse"

[ERROR]   CartTest.totalsPriceTimesQuantity:25 
expected: 7999L
 but was: 6499L
[ERROR] Tests run: 3, Failures: 2, Errors: 0, Skipped: 0
[ERROR] BUILD FAILURE
What’s happening
  1. listsItemsInOrder expects ["Mouse", "Keyboard"] but the cart keeps insertion order. AssertJ prints the actual list, the expected one, and each index that differs: much more than Jest's diff for a two-element array, and the same idea.
  2. totalsPriceTimesQuantity fails because the buggy totalCents ignores the quantity: expected: 7999L but was: 6499L (4999 + 1500). The L says the values were compared as long.
  3. Each failure is named by class, method and the line of the failing assertion: CartTest.listsItemsInOrder:20 and CartTest.totalsPriceTimesQuantity:25, which is enough to jump straight to it.
  4. Tests run: 3, Failures: 2 and BUILD FAILURE. A failing test stops the Maven build at the test phase, so ./mvnw package would produce no JAR (chapter 11).

#Parameterised tests

Added

When several tests differ only in their inputs and expected result, write one test method and feed it rows. That's Jest's it.each, and in JUnit it's @ParameterizedTest plus a source of arguments:

SourceGivesUse it for
@ValueSource(strings = {…})one argument per runa list of values that should all behave the same
@NullAndEmptySourcenull, then ""the edge cases of string inputs
@CsvSource({"0, 499", …})several arguments per row, converted to the parameter typesinput → expected tables
@MethodSource("name")whatever a static method returns (Stream<Arguments>)objects, or cases that need code to build
@EnumSource(Status.class)each enum constantbehaviour per enum value

Each row runs as its own test: it's counted separately and fails separately, so one bad row doesn't hide the others.

src/main/java/com/example/shop/Pricing.java
package com.example.shop;

import java.util.regex.Pattern;

public class Pricing {
    private static final Pattern SKU = Pattern.compile("[A-Z]{3}-\\d{4}");

    public static boolean isValidSku(String sku) {
        return sku != null && SKU.matcher(sku).matches();
    }

    public static long shippingCents(long subtotalCents) {
        return subtotalCents >= 5000 ? 0 : 499;
    }

    public static long withTax(long cents, String province) {
        int percent = switch (province) {
            case "ON" -> 13;
            case "AB" -> 5;
            default -> throw new IllegalArgumentException("unknown province: " + province);
        };
        return cents + Math.round(cents * percent / 100.0);
    }
}
src/test/java/com/example/shop/PricingTest.java
package com.example.shop;

import java.util.stream.Stream;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.params.provider.Arguments.arguments;

class PricingTest {
    @ParameterizedTest
    @ValueSource(strings = {"KEY-0001", "MOU-1234", "MON-9999"})
    void acceptsValidSkus(String sku) {
        assertThat(Pricing.isValidSku(sku)).isTrue();
    }

    @ParameterizedTest
    @NullAndEmptySource
    @ValueSource(strings = {"key-0001", "KEY-01", "KEY0001"})
    void rejectsInvalidSkus(String sku) {
        assertThat(Pricing.isValidSku(sku)).isFalse();
    }

    @ParameterizedTest(name = "{0} cents -> shipping {1}")
    @CsvSource({"0, 499", "4999, 499", "5000, 0", "12000, 0"})
    void shipping(long subtotal, long expected) {
        assertThat(Pricing.shippingCents(subtotal)).isEqualTo(expected);
    }

    static Stream<Arguments> taxCases() {
        return Stream.of(
                arguments(10000, "ON", 11300),
                arguments(10000, "AB", 10500),
                arguments(50, "ON", 57));
    }

    @ParameterizedTest
    @MethodSource("taxCases")
    void addsProvincialTax(long cents, String province, long expected) {
        assertThat(Pricing.withTax(cents, province)).isEqualTo(expected);
    }
}
Terminal
$ ./mvnw test
[INFO] Results:
[INFO] Tests run: 16, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
What’s happening
  1. acceptsValidSkus runs three times, once per string in @ValueSource, each time with sku set to that value.
  2. rejectsInvalidSkus combines two sources: @NullAndEmptySource adds null and "", and @ValueSource adds three malformed codes, so it runs five times. The null case is why isValidSku checks sku != null first; without it that run would fail with a NullPointerException.
  3. shipping gets two arguments per CSV row. JUnit converts the text "4999" to the long parameter by itself. The rows pin the boundary: 4999 still pays 499, 5000 is free. name = "{0} cents -> shipping {1}" sets how each run is labelled in reports.
  4. addsProvincialTax takes its rows from the static taxCases() method; the third row checks rounding (13% of 50 cents is 6.5, rounded to 7).
  5. The summary counts every run: 3 + 5 + 4 + 3 = 15 parameterised runs, plus contextLoads: Tests run: 16, Failures: 0.
AdvancedTip: CSV text blocks and CSV files

#Mockito

Added

A unit test tests one class with its collaborators replaced by test doubles, so a test of Checkout doesn't charge a real card or send a real email. Mockito makes those doubles. In Jest terms:

JestMockito
const pay = jest.fn()@Mock PaymentGateway payments (or mock(PaymentGateway.class))
pay.mockReturnValue("pay-42")when(payments.charge(…)).thenReturn("pay-42")
pay.mockImplementation(() => { throw … })when(…).thenThrow(new …)
expect(pay).toHaveBeenCalledWith("rohit", 3000)verify(payments).charge("rohit", 3000)
expect(pay).not.toHaveBeenCalled()verify(payments, never()).charge(…) / verifyNoInteractions(payments)
pay.mock.calls[0][1]an ArgumentCaptor
expect.any(String)anyString(), any(), eq(…)

The difference that matters: Jest can replace a module (jest.mock("./payments")) because JavaScript imports are dynamic. Mockito can't reach inside a class and swap what it creates with new; it creates a mock object, and you hand it to the class under test. That's why constructor injection (chapter 12) and testability go together: a class that receives its collaborators can be tested with mocks and no Spring at all.

src/main/java/com/example/shop/Checkout.java
package com.example.shop;

import java.util.Optional;

interface PaymentGateway {
    String charge(String customer, long cents);
}

interface ReceiptSender {
    void send(String customer, String text);
}

interface PriceList {
    Optional<Long> priceOf(String item);
}

class UnknownItemException extends RuntimeException {
    UnknownItemException(String item) {
        super("unknown item: " + item);
    }
}

public class Checkout {
    private final PriceList prices;
    private final PaymentGateway payments;
    private final ReceiptSender receipts;

    Checkout(PriceList prices, PaymentGateway payments, ReceiptSender receipts) {
        this.prices = prices;
        this.payments = payments;
        this.receipts = receipts;
    }

    public String buy(String customer, String item, int quantity) {
        long price = prices.priceOf(item).orElseThrow(() -> new UnknownItemException(item));
        String paymentId = payments.charge(customer, price * quantity);
        receipts.send(customer, quantity + " x " + item + ", payment " + paymentId);
        return paymentId;
    }
}
src/test/java/com/example/shop/CheckoutTest.java
package com.example.shop;

import java.util.Optional;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class CheckoutTest {
    @Mock
    PriceList prices;
    @Mock
    PaymentGateway payments;
    @Mock
    ReceiptSender receipts;
    @InjectMocks
    Checkout checkout;
    @Captor
    ArgumentCaptor<String> receiptText;

    @Test
    void chargesPriceTimesQuantityAndSendsReceipt() {
        when(prices.priceOf("Mouse")).thenReturn(Optional.of(1500L));
        when(payments.charge(anyString(), anyLong())).thenReturn("pay-42");

        String paymentId = checkout.buy("rohit", "Mouse", 2);

        assertThat(paymentId).isEqualTo("pay-42");
        verify(payments).charge("rohit", 3000);
        verify(receipts).send(eq("rohit"), receiptText.capture());
        assertThat(receiptText.getValue()).isEqualTo("2 x Mouse, payment pay-42");
    }

    @Test
    void unknownItemChargesNothing() {
        when(prices.priceOf("Laptop")).thenReturn(Optional.empty());

        assertThatThrownBy(() -> checkout.buy("rohit", "Laptop", 1))
                .isInstanceOf(UnknownItemException.class)
                .hasMessage("unknown item: Laptop");
        verifyNoInteractions(payments, receipts);
    }
}
Terminal
$ ./mvnw test
[INFO] Results:
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
What’s happening
  1. @ExtendWith(MockitoExtension.class) plugs Mockito into JUnit. Before each test it creates a mock for every @Mock field (an object that implements the interface and records every call), and @InjectMocks builds a real Checkout by passing those mocks to its constructor.
  2. A fresh mock returns "empty" values: null for objects, 0 for numbers, Optional.empty() for Optional. when(prices.priceOf("Mouse")).thenReturn(Optional.of(1500L)) stubs one call; anyString(), anyLong() makes the payment stub match any arguments.
  3. checkout.buy("rohit", "Mouse", 2) runs the real code against the mocks. verify(payments).charge("rohit", 3000) then checks the gateway was called exactly once with those arguments, which proves the price × quantity calculation.
  4. The receipt text is built inside buy, so the test captures it: receiptText.capture() inside verify grabs the argument, and getValue() returns "2 x Mouse, payment pay-42". (When one eq(…) matcher is used, every argument must be a matcher, hence eq("rohit").)
  5. unknownItemChargesNothing stubs an empty price, expects UnknownItemException, and checks with verifyNoInteractions that nobody was charged or emailed. Tests run: 3 with contextLoads.
AdvancedGotcha: strict stubs fail unused stubs
AdvancedWhat Mockito failures look like

The same test with two mistakes: verify expects the wrong amount, and the second test stubs a payment it never reaches.

src/main/java/com/example/shop/Checkout.java
package com.example.shop;

import java.util.Optional;

interface PaymentGateway {
    String charge(String customer, long cents);
}

interface ReceiptSender {
    void send(String customer, String text);
}

interface PriceList {
    Optional<Long> priceOf(String item);
}

class UnknownItemException extends RuntimeException {
    UnknownItemException(String item) {
        super("unknown item: " + item);
    }
}

public class Checkout {
    private final PriceList prices;
    private final PaymentGateway payments;
    private final ReceiptSender receipts;

    Checkout(PriceList prices, PaymentGateway payments, ReceiptSender receipts) {
        this.prices = prices;
        this.payments = payments;
        this.receipts = receipts;
    }

    public String buy(String customer, String item, int quantity) {
        long price = prices.priceOf(item).orElseThrow(() -> new UnknownItemException(item));
        String paymentId = payments.charge(customer, price * quantity);
        receipts.send(customer, quantity + " x " + item + ", payment " + paymentId);
        return paymentId;
    }
}
src/test/java/com/example/shop/CheckoutTest.java
package com.example.shop;

import java.util.Optional;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class CheckoutTest {
    @Mock
    PriceList prices;
    @Mock
    PaymentGateway payments;
    @Mock
    ReceiptSender receipts;
    @InjectMocks
    Checkout checkout;

    @Test
    void chargesPriceTimesQuantity() {
        when(prices.priceOf("Mouse")).thenReturn(Optional.of(1500L));
        when(payments.charge(anyString(), anyLong())).thenReturn("pay-42");

        checkout.buy("rohit", "Mouse", 2);

        verify(payments).charge("rohit", 1500);
    }

    @Test
    void unknownItemChargesNothing() {
        when(prices.priceOf("Laptop")).thenReturn(Optional.empty());
        when(payments.charge(anyString(), anyLong())).thenReturn("pay-1");

        assertThatThrownBy(() -> checkout.buy("rohit", "Laptop", 1))
                .isInstanceOf(UnknownItemException.class);
    }
}
Terminal
$ ./mvnw test
[INFO] Results:
[ERROR] Failures: 
[ERROR]   CheckoutTest.chargesPriceTimesQuantity:35 
Wanted but not invoked:
payments.charge("rohit", 1500L);
-> at com.example.shop.CheckoutTest.chargesPriceTimesQuantity(CheckoutTest.java:35)

However, there was exactly 1 interaction with this mock:
payments.charge("rohit", 3000L);
-> at com.example.shop.Checkout.buy(Checkout.java:36)


[ERROR] Errors: 
[ERROR]   CheckoutTest.unknownItemChargesNothing » UnnecessaryStubbing 
Unnecessary stubbings detected.
Clean & maintainable test code requires zero unnecessary code.
Following stubbings are unnecessary (click to navigate to relevant line of code):
  1. -> at com.example.shop.CheckoutTest.unknownItemChargesNothing(CheckoutTest.java:41)
Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.
[ERROR] Tests run: 3, Failures: 1, Errors: 1, Skipped: 0
[ERROR] BUILD FAILURE
What’s happening
  1. verify(payments).charge("rohit", 1500) fails with Wanted but not invoked, and Mockito lists the calls that did happen: payments.charge("rohit", 3000L), with the line in Checkout.buy that made it. That second half is usually the answer.
  2. It's reported under Failures, because a failed verification is an assertion failure.
  3. In unknownItemChargesNothing the code throws before reaching the gateway, so the payment stub is never used. After the test, the strict-stubs check reports UnnecessaryStubbing with the line of the unused stub. It's listed under Errors: the test body passed, and the extension failed it afterwards.
  4. Tests run: 3, Failures: 1, Errors: 1. In JUnit, a failure is a failed assertion and an error is any other exception; both fail the build.
AdvancedThe "self-attaching" warning on Java 21+

Mockito creates mocks by changing classes at run time, which needs a Java agent. Without one configured, it attaches itself while the tests run and prints a warning. It's hidden by Maven's summary, so here it is from the full output of the checkout-mocks suite:

Terminal
$ ./mvnw -q test 2>&1 | grep -c "self-attaching"
1
What’s happening
  1. -q makes Maven quiet but still shows what the tests print; grep -c counts the lines containing self-attaching. There's one: Mockito's notice that it's self-attaching to enable the inline mock maker, that this will stop working in a future JDK, and that you should add Mockito as an agent to your build.
  2. The JDK has been tightening dynamic agent loading since Java 21 (JEP 451), and Mockito's own docs now say to configure the agent explicitly. Spring Boot 4.2's parent pom doesn't do it for you.
  3. Today it's only a warning and every test still passes. The fix, from Mockito's documentation, goes in the <build> section of pom.xml (shown below).
XML
<properties>
	<java.version>25</java.version>
	<argLine/>
</properties>
...
<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-dependency-plugin</artifactId>
	<executions>
		<execution>
			<goals>
				<goal>properties</goal>
			</goals>
		</execution>
	</executions>
</plugin>
<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-surefire-plugin</artifactId>
	<configuration>
		<argLine>@{argLine} -javaagent:${org.mockito:mockito-core:jar}</argLine>
	</configuration>
</plugin>

The dependency plugin's properties goal sets a property holding each dependency's jar path, so ${org.mockito:mockito-core:jar} is the path to Mockito, and Surefire starts the test JVM with it as an agent. The empty <argLine/> property stops @{argLine} from breaking when no other plugin (such as JaCoCo for coverage) sets it. This excerpt isn't one of the page's checked suites; it was tried in a copy of the starter while writing this chapter, where the count above dropped from 1 to 0 and the tests still passed.

#Spring Boot tests: the full context and test slices

Added

A Spring test starts a Spring application context inside the test, so beans can be injected into the test class with @Autowired. The question is how much of the application to start:

AnnotationStartsTypical useSpeed
@SpringBootTestthe whole application context (with a real server if you ask for RANDOM_PORT)integration tests across layersslowest
@WebMvcTest(ProductController.class)MVC infrastructure + the named controllers, advice and filters; no services or repositoriescontroller tests with mocked servicesfast
@DataJpaTestJPA, the repositories and an embedded database; no web layer or servicesrepository and query testsfast
none (plain JUnit + Mockito)no Spring at allunit tests of services and domain logicfastest

The middle two are test slices: Boot applies only the auto-configuration for one layer. Whatever the slice leaves out, but your code still needs, you provide with @MockitoBean: it puts a Mockito mock into the context in place of the real bean (the next topic uses it). In Boot 3 this was @MockBean; Boot 4 removed @MockBean and @SpyBean, and the replacements, @MockitoBean and @MockitoSpyBean, come from Spring Framework itself (package org.springframework.test.context.bean.override.mockito). Also new in Boot 4: the test annotations moved into per-technology modules, so @DataJpaTest is now org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest, and the starter's spring-boot-starter-data-jpa-test brings it in.

@DataJpaTest also wraps every test in a transaction that's rolled back at the end, so tests can't see each other's rows:

src/main/java/com/example/shop/Product.java
package com.example.shop;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private long priceCents;

    protected Product() {
    }

    public Product(String name, long priceCents) {
        this.name = name;
        this.priceCents = priceCents;
    }

    public String getName() {
        return name;
    }
}
src/main/java/com/example/shop/ProductRepository.java
package com.example.shop;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findByPriceCentsLessThanOrderByPriceCents(long cents);
}
src/test/java/com/example/shop/ProductRepositoryTest.java
package com.example.shop;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
import org.springframework.boot.jpa.test.autoconfigure.TestEntityManager;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
class ProductRepositoryTest {
    @Autowired
    TestEntityManager em;
    @Autowired
    ProductRepository products;

    @Test
    void findsCheaperProductsInPriceOrder() {
        em.persist(new Product("Monitor", 29999));
        em.persist(new Product("Keyboard", 4999));
        em.persist(new Product("Mouse", 1500));

        assertThat(products.findByPriceCentsLessThanOrderByPriceCents(10000))
                .extracting(Product::getName)
                .containsExactly("Mouse", "Keyboard");
    }

    @Test
    void startsWithAnEmptyTable() {
        em.persist(new Product("Trackball", 5999));

        assertThat(products.count()).isEqualTo(1);
    }
}
Terminal
$ ./mvnw test
[INFO] Results:
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
What’s happening
  1. @DataJpaTest starts only the JPA part of the application: the H2 database, Hibernate (creating the tables from the entities) and the repositories. Controllers and services aren't created, so this context starts faster than the full app.
  2. TestEntityManager is a test helper around the EntityManager; persist inserts the test data directly, so the test doesn't depend on the repository methods it isn't testing.
  3. findsCheaperProductsInPriceOrder checks the derived query really filters and sorts: extracting(Product::getName) turns the entities into names, then containsExactly("Mouse", "Keyboard").
  4. startsWithAnEmptyTable inserts one product and expects a count of exactly 1. That holds whichever test runs first, because each test's transaction is rolled back when it ends: the three products from the other test are gone.
  5. Tests run: 3, Failures: 0, counting contextLoads. Repository tests like this catch mapping mistakes and query typos; they don't prove the SQL works on your production database (H2 isn't PostgreSQL), which is what Testcontainers is for.
AdvancedGotcha: rollback can hide flush errors
AdvancedContext caching: why test suites stay fast

Starting a context takes seconds, so Spring's test framework caches contexts and reuses one for every test class with the same configuration (same annotations, properties, @MockitoBeans and so on). Two classes with identical setups share a context; a class that adds a @MockitoBean gets a new one. Spring logs its cache statistics at debug level, so you can count how many contexts a run really created:

src/main/java/com/example/shop/Product.java
package com.example.shop;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;

@Entity
public class Product {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
}
src/main/java/com/example/shop/ProductRepository.java
package com.example.shop;

import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Long> {
}
src/test/java/com/example/shop/CatalogTest.java
package com.example.shop;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest
class CatalogTest {
    @Autowired
    ProductRepository products;

    @Test
    void startsEmpty() {
        assertThat(products.count()).isZero();
    }
}
src/test/java/com/example/shop/CatalogWithMockTest.java
package com.example.shop;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.bean.override.mockito.MockitoBean;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;

@SpringBootTest
class CatalogWithMockTest {
    @MockitoBean
    ProductRepository products;
    @Autowired
    ProductRepository injected;

    @Test
    void usesTheMock() {
        when(products.count()).thenReturn(42L);
        assertThat(injected.count()).isEqualTo(42);
    }
}
src/test/java/com/example/shop/ProductRepositoryTest.java
package com.example.shop;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
class ProductRepositoryTest {
    @Autowired
    ProductRepository products;

    @Test
    void startsEmpty() {
        assertThat(products.count()).isZero();
    }
}
src/test/resources/application.properties
spring.application.name=shop
logging.level.org.springframework.test.context.cache=debug
Terminal
$ ./mvnw test
[INFO] Results:
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
$ ./mvnw -q test 2>&1 | grep -o "missCount = [0-9]*" | tail -1
missCount = 3
What’s happening
  1. Four test classes run: the starter's ShopApplicationTests (@SpringBootTest), CatalogTest (also plain @SpringBootTest), CatalogWithMockTest (@SpringBootTest plus a @MockitoBean) and ProductRepositoryTest (@DataJpaTest). All pass: Tests run: 4.
  2. src/test/resources/application.properties replaces the main one during tests and turns on debug logging for Spring's context cache, which then prints its statistics each time a test asks for a context. A miss is a context the cache didn't have, so Spring had to create it.
  3. The last statistics line says missCount = 3: four classes, three contexts. ShopApplicationTests and CatalogTest have the same configuration, so whichever runs second reuses the first one's context.
  4. CatalogWithMockTest declares @MockitoBean ProductRepository, which changes the configuration (the repository bean is replaced by a mock, and injected receives that mock: count() returns the stubbed 42), so it needs its own context. @DataJpaTest is a different slice: the third context.
  5. In a big suite, every distinct combination of @MockitoBeans, properties and profiles costs a context start. Teams keep suites fast by sharing a few base configurations (an abstract test class or a custom annotation) instead of a slightly different set of mocks in every class.

#Testing controllers

Added

A controller test should check what a client sees: the URL mapping, the status code, the JSON body, validation errors. Spring offers two clients for that, both new or reworked in recent versions:

  • MockMvcTester (Spring 6.2+): sends requests through Spring MVC without a server or network, and asserts with AssertJ. Use it with @WebMvcTest, where it's auto-configured, or with @SpringBootTest plus @AutoConfigureMockMvc (Boot 4's @SpringBootTest no longer sets up MockMvc on its own). It's the AssertJ-style successor of the older MockMvc with perform(…).andExpect(…), which still works.
  • RestTestClient (Spring 7 / Boot 4): a fluent client that can hit a real running server (@SpringBootTest(webEnvironment = RANDOM_PORT) plus @AutoConfigureRestTestClient) or MockMvc. It replaces TestRestTemplate, deprecated in Boot 4.2.

In Express terms, MockMvcTester is like Supertest calling your app in-process, and RestTestClient against RANDOM_PORT is like Supertest against a listening server. The controller here is deliberately small; chapter 13 covers controllers properly.

src/main/java/com/example/shop/Product.java
package com.example.shop;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private long priceCents;

    protected Product() {
    }

    public Product(String name, long priceCents) {
        this.name = name;
        this.priceCents = priceCents;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public long getPriceCents() {
        return priceCents;
    }
}
src/main/java/com/example/shop/ProductService.java
package com.example.shop;

import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

interface ProductRepository extends JpaRepository<Product, Long> {
}

record ProductView(long id, String name, long priceCents) {
    static ProductView of(Product p) {
        return new ProductView(p.getId(), p.getName(), p.getPriceCents());
    }
}

@Service
public class ProductService {
    private final ProductRepository products;

    ProductService(ProductRepository products) {
        this.products = products;
    }

    public Optional<ProductView> find(long id) {
        return products.findById(id).map(ProductView::of);
    }

    public ProductView create(String name, long priceCents) {
        return ProductView.of(products.save(new Product(name, priceCents)));
    }
}
src/main/java/com/example/shop/ProductController.java
package com.example.shop;

import java.net.URI;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
class ProductController {
    record NewProduct(@NotBlank String name, @Positive long priceCents) {
    }

    private final ProductService service;

    ProductController(ProductService service) {
        this.service = service;
    }

    @GetMapping("/products/{id}")
    ResponseEntity<ProductView> get(@PathVariable long id) {
        return ResponseEntity.of(service.find(id));
    }

    @PostMapping("/products")
    ResponseEntity<ProductView> create(@Valid @RequestBody NewProduct body) {
        ProductView saved = service.create(body.name(), body.priceCents());
        return ResponseEntity.created(URI.create("/products/" + saved.id())).body(saved);
    }
}
src/test/java/com/example/shop/ProductControllerTest.java
package com.example.shop;

import java.util.Optional;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.assertj.MockMvcTester;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

@WebMvcTest(ProductController.class)
class ProductControllerTest {
    @Autowired
    MockMvcTester mvc;

    @MockitoBean
    ProductService service;

    @Test
    void returnsAProductAsJson() {
        when(service.find(7)).thenReturn(Optional.of(new ProductView(7, "Keyboard", 4999)));

        assertThat(mvc.get().uri("/products/7"))
                .hasStatusOk()
                .bodyJson().isLenientlyEqualTo("""
                        {"id": 7, "name": "Keyboard", "priceCents": 4999}
                        """);
    }

    @Test
    void unknownProductIs404() {
        when(service.find(99)).thenReturn(Optional.empty());

        assertThat(mvc.get().uri("/products/99")).hasStatus(HttpStatus.NOT_FOUND);
    }

    @Test
    void blankNameIs400AndSavesNothing() {
        assertThat(mvc.post().uri("/products")
                .contentType(MediaType.APPLICATION_JSON)
                .content("""
                        {"name": " ", "priceCents": 4999}
                        """))
                .hasStatus(HttpStatus.BAD_REQUEST);
        verifyNoInteractions(service);
    }
}
Terminal
$ ./mvnw test
[INFO] Results:
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
What’s happening
  1. @WebMvcTest(ProductController.class) starts Spring MVC with just that controller (plus JSON and validation support). ProductService isn't created, so @MockitoBean puts a Mockito mock of it into the context, and the controller receives the mock.
  2. returnsAProductAsJson stubs the service, then mvc.get().uri("/products/7") sends a GET through the whole MVC stack (routing, argument conversion, Jackson) without opening a socket. hasStatusOk() checks 200, and bodyJson().isLenientlyEqualTo(…) compares the JSON by value, ignoring field order and formatting.
  3. unknownProductIs404: the service returns an empty Optional, ResponseEntity.of turns that into a 404, and the test pins it with hasStatus(HttpStatus.NOT_FOUND).
  4. blankNameIs400AndSavesNothing posts a name of " ". @Valid with @NotBlank rejects it before the controller method runs, so the response is a 400 and verifyNoInteractions(service) proves nothing was saved.
  5. Tests run: 4, Failures: 0 (three controller tests plus contextLoads). This is the right level for the HTTP contract: the mapping, statuses and validation, with the business logic mocked away and tested elsewhere.
AdvancedNote: JSON paths, headers and exceptions
AdvancedEnd to end with RestTestClient and a real server

For a few tests you want the real thing: a server on a random port, the real service, the real database. Same application files, with ProductApiTest:

src/main/java/com/example/shop/Product.java
package com.example.shop;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private long priceCents;

    protected Product() {
    }

    public Product(String name, long priceCents) {
        this.name = name;
        this.priceCents = priceCents;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public long getPriceCents() {
        return priceCents;
    }
}
src/main/java/com/example/shop/ProductService.java
package com.example.shop;

import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

interface ProductRepository extends JpaRepository<Product, Long> {
}

record ProductView(long id, String name, long priceCents) {
    static ProductView of(Product p) {
        return new ProductView(p.getId(), p.getName(), p.getPriceCents());
    }
}

@Service
public class ProductService {
    private final ProductRepository products;

    ProductService(ProductRepository products) {
        this.products = products;
    }

    public Optional<ProductView> find(long id) {
        return products.findById(id).map(ProductView::of);
    }

    public ProductView create(String name, long priceCents) {
        return ProductView.of(products.save(new Product(name, priceCents)));
    }
}
src/main/java/com/example/shop/ProductController.java
package com.example.shop;

import java.net.URI;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
class ProductController {
    record NewProduct(@NotBlank String name, @Positive long priceCents) {
    }

    private final ProductService service;

    ProductController(ProductService service) {
        this.service = service;
    }

    @GetMapping("/products/{id}")
    ResponseEntity<ProductView> get(@PathVariable long id) {
        return ResponseEntity.of(service.find(id));
    }

    @PostMapping("/products")
    ResponseEntity<ProductView> create(@Valid @RequestBody NewProduct body) {
        ProductView saved = service.create(body.name(), body.priceCents());
        return ResponseEntity.created(URI.create("/products/" + saved.id())).body(saved);
    }
}
src/test/java/com/example/shop/ProductApiTest.java
package com.example.shop;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.client.RestTestClient;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureRestTestClient
class ProductApiTest {
    @Autowired
    RestTestClient client;

    @Test
    void createThenFetch() {
        client.post().uri("/products")
                .contentType(MediaType.APPLICATION_JSON)
                .body("""
                        {"name": "Keyboard", "priceCents": 4999}
                        """)
                .exchange()
                .expectStatus().isCreated()
                .expectHeader().valueEquals("Location", "/products/1");

        client.get().uri("/products/1")
                .exchange()
                .expectStatus().isOk()
                .expectBody().jsonPath("$.name").isEqualTo("Keyboard");
    }
}
Terminal
$ ./mvnw test
[INFO] Results:
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
What’s happening
  1. webEnvironment = RANDOM_PORT starts the full application with embedded Tomcat on a free port, so tests can run in parallel with other apps on the machine. @AutoConfigureRestTestClient creates a RestTestClient already pointed at that port.
  2. The POST goes over real HTTP into the real controller, service, repository and H2 database. expectStatus().isCreated() checks the 201, and expectHeader() checks Location: /products/1.
  3. The GET reads the product back through the API, and jsonPath("$.name") checks one field of the JSON.
  4. Nothing is mocked and nothing is rolled back (the request ran on Tomcat's thread, in its own committed transaction). Tests run: 2: this test and contextLoads, which needs its own context because a server on a random port is a different configuration.
  5. Keep these few: they're the slowest and least precise when they fail. One or two per important flow proves the wiring, while slices and unit tests cover the cases.

#Testcontainers

Added

H2 is convenient, but it isn't your production database. Native queries, PostgreSQL types (jsonb, arrays), full-text search, locking behaviour and migration scripts can pass on H2 and fail on PostgreSQL, or the other way round. Testcontainers starts a real database in a Docker container for the test, and throws it away afterwards. In Node you'd reach for the testcontainers npm package or a docker compose service in CI; it's the same project family.

Spring Boot's @ServiceConnection removes the wiring: put it on the container field and Boot points the DataSource at the container (its random port, username and password) instead of reading spring.datasource.* properties. The test needs Docker running on the machine. The first run downloads the postgres image (and Testcontainers' small ryuk helper, which removes containers when the JVM exits), which can take a while; later runs start the container in a few seconds.

Testcontainers 2 renamed its modules: the artifacts now start with testcontainers-, and the PostgreSQL container class moved to org.testcontainers.postgresql.PostgreSQLContainer and lost its generic type parameter (the old org.testcontainers.containers.PostgreSQLContainer still exists in 2.0.5, marked deprecated). Add these to pom.xml (the same entries start.spring.io generates):

pom.xml
		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-testcontainers</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.testcontainers</groupId>
			<artifactId>testcontainers-junit-jupiter</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.testcontainers</groupId>
			<artifactId>testcontainers-postgresql</artifactId>
			<scope>test</scope>
		</dependency>
src/main/java/com/example/shop/Product.java
package com.example.shop;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    protected Product() {
    }

    public Product(String name) {
        this.name = name;
    }
}
src/main/java/com/example/shop/ProductRepository.java
package com.example.shop;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface ProductRepository extends JpaRepository<Product, Long> {
    @Query(value = """
            select name from product
            where to_tsvector('english', name) @@ plainto_tsquery('english', :words)
            order by name""", nativeQuery = true)
    List<String> search(String words);
}
src/test/java/com/example/shop/ProductSearchTest.java
package com.example.shop;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.postgresql.PostgreSQLContainer;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest(properties = "spring.jpa.hibernate.ddl-auto=create-drop")
@Testcontainers
class ProductSearchTest {
    @Container
    @ServiceConnection
    static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:18");

    @Autowired
    ProductRepository products;

    @Test
    void searchesWithPostgresFullText() {
        products.save(new Product("Mechanical keyboards"));
        products.save(new Product("Wireless mouse"));
        products.save(new Product("Keyboard tray"));

        assertThat(products.search("keyboard")).containsExactly("Keyboard tray", "Mechanical keyboards");
        assertThat(products.count()).isEqualTo(3);
    }
}
Terminal
$ ./mvnw test
[INFO] Results:
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
What’s happening
  1. @Testcontainers lets JUnit manage the @Container fields: a static field is started once before the class's tests and stopped after them (an instance field would get a new container per test). new PostgreSQLContainer("postgres:18") picks the image; pin the same major version you run in production.
  2. @ServiceConnection tells Boot to build the DataSource from the running container. @DataJpaTest normally swaps in an embedded database, but it sees the service connection and leaves it alone, so the repository talks to real PostgreSQL 18.
  3. ddl-auto=create-drop is needed because Boot only creates tables automatically for embedded databases. Without it, the first insert fails with PostgreSQL's ERROR: relation "product" does not exist (that's what happened on the first try while writing this). In a real project Flyway would create the schema from your migrations, which tests them too.
  4. The search uses PostgreSQL full-text search: to_tsvector('english', name) reduces words to stems, so the query keyboard matches both "Keyboard tray" and "Mechanical keyboards", but not the mouse.
  5. Tests run: 2, Failures: 0. The starter's contextLoads still uses H2, since it has no container; only ProductSearchTest touches PostgreSQL. When the JVM exits, Testcontainers removes the container.
AdvancedTip: sharing containers and dev-time containers
AdvancedThe same test on H2

Remove the container, and the very same test runs on H2, which has no full-text functions:

src/main/java/com/example/shop/Product.java
package com.example.shop;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    protected Product() {
    }

    public Product(String name) {
        this.name = name;
    }
}
src/main/java/com/example/shop/ProductRepository.java
package com.example.shop;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface ProductRepository extends JpaRepository<Product, Long> {
    @Query(value = """
            select name from product
            where to_tsvector('english', name) @@ plainto_tsquery('english', :words)
            order by name""", nativeQuery = true)
    List<String> search(String words);
}
src/test/java/com/example/shop/ProductSearchTest.java
package com.example.shop;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
class ProductSearchTest {
    @Autowired
    ProductRepository products;

    @Test
    void searchesWithPostgresFullText() {
        products.save(new Product("Mechanical keyboards"));
        products.save(new Product("Wireless mouse"));
        products.save(new Product("Keyboard tray"));

        assertThat(products.search("keyboard")).containsExactly("Keyboard tray", "Mechanical keyboards");
    }
}
Terminal
$ ./mvnw test
[INFO] Results:
[ERROR] Errors: 
[ERROR]   ProductSearchTest.searchesWithPostgresFullText:20 » InvalidDataAccessResourceUsage Could not prepare statement [Function "TO_TSVECTOR" not found; SQL statement:
select name from product
where to_tsvector('english', name) @@ plainto_tsquery('english', ?)
order by name [90022-252]] [select name from product
where to_tsvector('english', name) @@ plainto_tsquery('english', ?)
order by name]; SQL [select name from product
where to_tsvector('english', name) @@ plainto_tsquery('english', ?)
order by name]
[ERROR] Tests run: 2, Failures: 0, Errors: 1, Skipped: 0
[ERROR] BUILD FAILURE
What’s happening
  1. Without a service connection, @DataJpaTest uses the embedded H2 database, and Hibernate creates the table there automatically.
  2. The native query reaches H2 unchanged, and H2 rejects it: Function "TO_TSVECTOR" not found, wrapped by Spring in an InvalidDataAccessResourceUsage error. It counts under Errors, not Failures, because no assertion ran.
  3. Here H2 at least fails loudly. The worse case is a query that works on both but behaves differently (sorting with collations, case sensitivity, date arithmetic), which passes on H2 and breaks in production. That's the argument for running repository tests against the real database.

#What to test in a Spring Boot service

Added

The test pyramid for a backend: many fast tests at the bottom, a few slow ones at the top. Each layer proves something the others can't:

KindToolsProvesDoesn't prove
UnitJUnit, AssertJ, Mockitobusiness rules and edge cases, in millisecondswiring, SQL, HTTP mapping
Web slice@WebMvcTest, MockMvcTester, @MockitoBeanroutes, status codes, validation, JSON shape, error handlingthat the service and database behave
Data slice@DataJpaTest, Testcontainersqueries, mappings, migrations on the real enginethe HTTP layer
Integration@SpringBootTest(RANDOM_PORT), RestTestClient, Testcontainersthe app starts and a request flows through every layerevery case (too slow to cover them all)
Contract / end to endSpring Cloud Contract, Pact, a deployed environmentother services agree with your APIquick feedback

A useful rule: test each behaviour at the lowest level that can prove it. A discount rule belongs in a unit test; "blank names get a 400" in a web slice; "this query uses PostgreSQL's jsonb operators correctly" in a data slice with Testcontainers; "an order can be placed" in one integration test. When a bug escapes, ask which layer should have caught it and add the test there. In Node terms it's the same split you'd make with Jest unit tests, Supertest against the Express app, and a few tests against a real database.

What not to spend tests on: getters and setters, Spring's own behaviour (that @Autowired works), and framework configuration you'd only be re-asserting. Coverage numbers (JaCoCo is the Java tool) show what's untested; they don't show what's tested well.

#Your turn: testing

Added
Your turn: a table of SKUs

Rewrite the two SKU tests from Parameterised tests as one @CsvSource test whose rows hold the SKU and whether it's valid. Include a lower-case SKU and a SKU with too few digits.

Show answer
src/main/java/com/example/shop/Pricing.java
package com.example.shop;

import java.util.regex.Pattern;

public class Pricing {
    private static final Pattern SKU = Pattern.compile("[A-Z]{3}-\\d{4}");

    public static boolean isValidSku(String sku) {
        return sku != null && SKU.matcher(sku).matches();
    }
}
src/test/java/com/example/shop/PricingTest.java
package com.example.shop;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

import static org.assertj.core.api.Assertions.assertThat;

class PricingTest {
    @ParameterizedTest(name = "{0} valid? {1}")
    @CsvSource({
            "KEY-0001, true",
            "MOU-1234, true",
            "key-0001, false",
            "KEY-01, false",
            "KEY0001, false"
    })
    void checksSkus(String sku, boolean valid) {
        assertThat(Pricing.isValidSku(sku)).isEqualTo(valid);
    }
}
Terminal
$ ./mvnw test
[INFO] Results:
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
What’s happening
  1. Each CSV row supplies the SKU and the expected answer; JUnit converts true/false to the boolean parameter.
  2. One method now covers both directions, and adding a case is one line. The name pattern labels each run like KEY-01 valid? false in reports.
  3. Five rows plus contextLoads: Tests run: 6, Failures: 0. (@CsvSource can't express null as easily: an empty unquoted value becomes null, or keep @NullAndEmptySource on a separate test.)
Your turn: a declined payment sends no receipt

With the Checkout class from Mockito, write a test where the payment gateway throws IllegalStateException("card declined"). Assert that buy throws it too and that no receipt is sent.

Show answer
src/main/java/com/example/shop/Checkout.java
package com.example.shop;

import java.util.Optional;

interface PaymentGateway {
    String charge(String customer, long cents);
}

interface ReceiptSender {
    void send(String customer, String text);
}

interface PriceList {
    Optional<Long> priceOf(String item);
}

public class Checkout {
    private final PriceList prices;
    private final PaymentGateway payments;
    private final ReceiptSender receipts;

    Checkout(PriceList prices, PaymentGateway payments, ReceiptSender receipts) {
        this.prices = prices;
        this.payments = payments;
        this.receipts = receipts;
    }

    public String buy(String customer, String item, int quantity) {
        long price = prices.priceOf(item).orElseThrow();
        String paymentId = payments.charge(customer, price * quantity);
        receipts.send(customer, quantity + " x " + item + ", payment " + paymentId);
        return paymentId;
    }
}
src/test/java/com/example/shop/CheckoutTest.java
package com.example.shop;

import java.util.Optional;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class CheckoutTest {
    @Mock
    PriceList prices;
    @Mock
    PaymentGateway payments;
    @Mock
    ReceiptSender receipts;
    @InjectMocks
    Checkout checkout;

    @Test
    void declinedPaymentSendsNoReceipt() {
        when(prices.priceOf("Mouse")).thenReturn(Optional.of(1500L));
        when(payments.charge("rohit", 1500)).thenThrow(new IllegalStateException("card declined"));

        assertThatThrownBy(() -> checkout.buy("rohit", "Mouse", 1))
                .isInstanceOf(IllegalStateException.class)
                .hasMessage("card declined");
        verify(receipts, never()).send(any(), any());
    }
}
Terminal
$ ./mvnw test
[INFO] Results:
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
What’s happening
  1. thenThrow makes the mock throw when charge("rohit", 1500) is called, the Mockito version of Jest's mockImplementation(() => { throw … }).
  2. buy doesn't catch it, so the exception reaches the test, where assertThatThrownBy checks its type and message.
  3. verify(receipts, never()).send(any(), any()) proves the receipt line was never reached. Both stubs were used, so strict stubs is happy: Tests run: 2, Failures: 0.
Your turn: test a search query

Add List<Product> findByNameContainingIgnoreCase(String text) to a repository and write a @DataJpaTest showing that searching for "MOUSE" finds both mice and not the keyboard.

Show answer
src/main/java/com/example/shop/Product.java
package com.example.shop;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    protected Product() {
    }

    public Product(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}
src/main/java/com/example/shop/ProductRepository.java
package com.example.shop;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Long> {
    List<Product> findByNameContainingIgnoreCase(String text);
}
src/test/java/com/example/shop/ProductRepositoryTest.java
package com.example.shop;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
import org.springframework.boot.jpa.test.autoconfigure.TestEntityManager;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
class ProductRepositoryTest {
    @Autowired
    TestEntityManager em;
    @Autowired
    ProductRepository products;

    @Test
    void searchIgnoresCase() {
        em.persist(new Product("Wireless mouse"));
        em.persist(new Product("Gaming Mouse"));
        em.persist(new Product("Mechanical keyboard"));

        assertThat(products.findByNameContainingIgnoreCase("MOUSE"))
                .extracting(Product::getName)
                .containsExactlyInAnyOrder("Wireless mouse", "Gaming Mouse");
    }
}
Terminal
$ ./mvnw test
[INFO] Results:
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
What’s happening
  1. @DataJpaTest starts JPA with H2; TestEntityManager inserts three products inside the test's transaction.
  2. ContainingIgnoreCase becomes upper(name) like upper(?) with the value wrapped in %…%, so "MOUSE" matches "Wireless mouse" and "Gaming Mouse".
  3. The query has no order by, so the test uses containsExactlyInAnyOrder rather than relying on the database's row order. Tests run: 2, Failures: 0, and the transaction is rolled back afterwards.

Written fresh, no doc. Examples were run with Eclipse Temurin 25.0.5.1 and Spring Boot 4.2.0 (Maven 3.10.1); facts come from openjdk.org, docs.oracle.com and spring.io, read 2026-11-26.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.