Skip to content
Visual explainer 5h to learn 5 steps

Testing Spring apps & Testcontainers

Write slice and integration tests against a real database.

By Invicly Tech, , in Backend Java Development. About 10 minutes to read.

Topic 22 of 29

In short

Spring offers test slices that start only part of the app, plus full @SpringBootTest integration tests. Testcontainers runs a real Postgres in Docker so repository tests match production.

Explained simply

Tests prove your code still works after every change. In a Spring app there are different kinds. A unit test checks one class alone, with no Spring at all, and runs in milliseconds. A slice test starts only one layer, such as the web layer. An integration test starts the whole app and calls it like a real client.

A good test suite is shaped like a pyramid: many fast unit tests at the bottom, fewer slice tests in the middle, and a handful of full integration tests on top. Each layer catches different bugs. Wiring mistakes only show up when the whole app starts; logic bugs are cheaper to catch in unit tests.

Databases are where tests often lie. An in-memory database like H2 speaks a slightly different SQL from PostgreSQL, so a query can pass in tests and fail in production. Testcontainers fixes this by starting a real PostgreSQL in Docker for the test run, then throwing it away afterwards.

Security needs testing too. You want proof that a missing token gives 401, a normal user gets 403 on admin pages, and the right user gets 200. Spring Security's test support lets you pretend to be any user in one line.

Press Play on a diagram to walk through it one step at a time.

CompareChoosing a Spring test type
@WebMvcTest
  • Loads controllers only
  • Services are mocked
  • Uses MockMvc, no server
  • Fast
@DataJpaTest
  • Loads JPA and repositories
  • Rolls back after each test
  • Pair with Testcontainers
  • Medium speed
@SpringBootTest
  • Loads the whole app
  • Real HTTP on a random port
  • Catches wiring problems
  • Slowest
LayersThe Spring test pyramid
  1. 1
    Few: @SpringBootTest + Testcontainers

    Whole app, real HTTP, real database

  2. 2
    Some: @WebMvcTest

    Routing, validation, JSON, security rules

  3. 3
    Some: @DataJpaTest

    Queries and mappings on real Postgres

  4. 4
    Many: plain JUnit unit tests

    Business logic with no Spring context

In depth

The context cache: why test suites get slow

Starting a Spring application context takes seconds. To avoid paying that for every test class, Spring's TestContext framework caches contexts and reuses one whenever a later test class has exactly the same configuration. The cache key includes the annotations, active profiles, properties and the set of mocked beans.

That is why small differences cost a lot. One class with @MockitoBean PaymentClient and another with @MockitoBean EmailClient need two different contexts. @DirtiesContext throws a context away and forces a fresh start. In a big suite, build a few shared base classes or test configurations so most tests hit the same cached context. The cache holds up to 32 contexts by default (spring.test.context.cache.maxSize), and setting logging.level.org.springframework.test.context.cache=DEBUG prints hit and miss statistics.

  • Same configuration = cached context, started once per JVM
  • Each distinct set of @MockitoBean fields creates a new context
  • Avoid @DirtiesContext unless a test truly breaks shared state

What each slice loads, and what it leaves out

@WebMvcTest loads controllers, @ControllerAdvice, Jackson, converters, filters and MockMvc. It does not load @Service or @Repository beans, so you replace them with @MockitoBean (the newer name for @MockBean, which is deprecated since Boot 3.4). Name the controller, as in @WebMvcTest(BookController.class), to keep the context small. Spring Security is applied too; if your rules live in a @Configuration class, add @Import(SecurityConfig.class) so the test uses your real rules instead of Boot's defaults.

@DataJpaTest loads entities, repositories, the DataSource and Flyway or Liquibase. Each test runs in a transaction that is rolled back at the end, so tests do not see each other's data. By default it swaps your database for an embedded one; with Testcontainers add @AutoConfigureTestDatabase(replace = Replace.NONE). Because nothing is committed, call flush() (or saveAndFlush) when you want the database to actually check constraints inside the test.

CompareWhich beans each test type creates
@WebMvcTest
  • Controllers and advice
  • Jackson and validation
  • Security filters
  • No services or repositories
@DataJpaTest
  • Entities and repositories
  • DataSource and migrations
  • TestEntityManager
  • No controllers or services
@SpringBootTest
  • Every bean in the app
  • Real server on RANDOM_PORT
  • All config and profiles
  • Mocks only where you add them

Testcontainers lifecycle and speed

Testcontainers talks to your local Docker, pulls the image once, and starts a container on a random free port. A static field marked @Container starts once per test class and stops after it. A small helper container called Ryuk removes everything when the JVM exits, even after a crash.

With @ServiceConnection (Boot 3.1+), Boot reads the container's JDBC URL, user and password and configures the DataSource for you. The older way is @DynamicPropertySource, which you still need for settings @ServiceConnection does not cover. A PostgreSQL container usually starts in a few seconds. To share one container across all test classes, start it in a static block of a base class or define it as a @Bean in a @TestConfiguration; Spring's context cache then reuses it too. Pin the image tag, such as postgres:16-alpine, to the version production runs.

SequenceOne test class with a Postgres container
JUnit
Testcontainers
Docker
Spring context
  1. 1Start static @Container
    JUnit to Testcontainers: Start static @Container
  2. 2Run postgres:16 on a random port
    Testcontainers to Docker: Run postgres:16 on a random port
  3. 3Ready: database accepts connections
    Docker to Testcontainers: Ready: database accepts connections
  4. 4@ServiceConnection: JDBC URL and login
    Testcontainers to Spring context: @ServiceConnection: JDBC URL and login
  5. 5Flyway migrates, beans start
    Spring context to Spring context: Flyway migrates, beans start
  6. 6Run each test method
    JUnit to Spring context: Run each test method
  7. 7Stop container after the class
    Testcontainers to Docker: Stop container after the class

Testing secured endpoints

Add spring-security-test to get two kinds of helpers. Annotations such as @WithMockUser(roles = "ADMIN") put a fake authenticated user into the SecurityContext for one test. Request post-processors attach credentials to a single MockMvc call: jwt() for an OAuth2 resource server, user("bob").roles("USER") for a simple user, and csrf() when CSRF protection is on and you send a POST.

The jwt() helper skips the real signature check, so it tests your rules, not the token parsing. Add at least one @SpringBootTest that sends a real signed token to prove the decoder settings work. For each protected endpoint, cover three cases: no credentials (401), wrong role (403) and right role (200). Those three tests catch most security regressions, such as a rule accidentally moved below a broader permitAll.

  • @WithMockUser defaults to username user with role USER
  • with(jwt().authorities(new SimpleGrantedAuthority("ROLE_ADMIN"))) fakes an admin token
  • with(csrf()) is needed for POST in apps that keep CSRF on

Learn it in 5 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Test controllers with @WebMvcTest~1h
  2. 2
    Test repositories with @DataJpaTest~1h
  3. 3
    Write @SpringBootTest integration tests~1h
  4. 4
    Run Postgres with Testcontainers~1h
  5. 5
    Test secured endpoints~1h

Key points

  • Use slices for focused, fast tests and a few full tests for end-to-end wiring.
  • Testcontainers starts disposable Docker databases for realistic tests.
  • @ServiceConnection (Boot 3.1+) wires a container's URL into Spring automatically.
  • Test secured endpoints with @WithMockUser or by sending a real token.

Key terms

Tap a card to flip it. 0/5 known

Examples

java
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@Testcontainers
class OrderApiIT {
  @Container @ServiceConnection
  static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:16");

  @Autowired TestRestTemplate rest;

  @Test
  void createsOrder() {
    var res = rest.postForEntity("/api/orders", new CreateOrder("book", 2), OrderDto.class);
    assertEquals(HttpStatus.CREATED, res.getStatusCode());
  }
}

Controller test: validation error returns 400

You want proof that POST /api/books rejects a blank title without touching the database. Step 1: start only the web layer with @WebMvcTest(BookController.class). Step 2: replace the service with @MockitoBean. Step 3: send invalid JSON with a mock user and CSRF token. Step 4: expect 400 and verify the service was never called. This runs in well under a second once the context is cached.

java
@WebMvcTest(BookController.class)
class BookControllerTest {
  @Autowired MockMvc mvc;
  @MockitoBean BookService service;

  @Test @WithMockUser
  void rejectsBlankTitle() throws Exception {
    mvc.perform(post("/api/books").with(csrf())
            .contentType(MediaType.APPLICATION_JSON)
            .content("{\"title\":\"\",\"pages\":120}"))
       .andExpect(status().isBadRequest());
    verifyNoInteractions(service);
  }
}

Repository test on real PostgreSQL

A custom query uses ILIKE, which H2 handles differently from PostgreSQL. Step 1: annotate the class with @DataJpaTest and keep the real database with Replace.NONE. Step 2: start a Postgres container with @ServiceConnection. Step 3: Flyway creates the schema from your migrations. Step 4: save rows, run the query, check the result. The test transaction rolls back at the end, so the next test starts clean.

java
@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
@Testcontainers
class BookRepositoryTest {
  @Container @ServiceConnection
  static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:16-alpine");

  @Autowired BookRepository books;

  @Test
  void searchIsCaseInsensitive() {
    books.saveAndFlush(new Book("Clean Code"));
    assertThat(books.searchTitle("%clean%")).hasSize(1);
  }
}

Quick reference

  • @WebMvcTest(XController.class) + @MockitoBean for services: fast web-layer tests
  • @DataJpaTest rolls back each test; flush() to make the database check constraints
  • @AutoConfigureTestDatabase(replace = Replace.NONE) keeps your Testcontainers database
  • @SpringBootTest(webEnvironment = RANDOM_PORT) starts a real server on a free port
  • @ServiceConnection wires a container's URL and login into Spring (Boot 3.1+)
  • @MockitoBean replaces the deprecated @MockBean (Spring Framework 6.2, Boot 3.4)
  • Security tests: no token gives 401, wrong role 403, right role 200
  • Different mocks or properties per class mean new contexts and a slower suite

Common mistakes

  • Using H2 in tests while production runs Postgres, hiding SQL differences.
  • Making every test a @SpringBootTest, so the suite becomes slow.
  • Tests that share data and pass or fail depending on order.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which beans does @WebMvcTest NOT create?

Question 2

2A @DataJpaTest saves an entity that breaks a unique constraint, yet the test passes. What is the likely reason?

Question 3

3Your suite starts the Spring context 40 times. What is the most likely cause?

Question 4

4What does @ServiceConnection do on a Testcontainers field?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a plain unit test (no Spring) for a PriceCalculator that gives 10% off orders over 100.

  2. Exercise 2medium

    Write three MockMvc tests for GET /api/admin/stats: no user gives 401, a USER gives 403, an ADMIN gives 200.

  3. Exercise 3hard

    Share one PostgreSQL container across all integration test classes so it starts only once per run.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is H2 good enough for tests?
For quick demos, maybe. For real projects it hides differences in SQL, types and locking from PostgreSQL or MySQL, so use Testcontainers with the same engine and version as production.
Do I need Docker in CI to use Testcontainers?
Yes, the CI runner needs a Docker-compatible engine. GitHub Actions Ubuntu runners have Docker installed, so it works out of the box.
What replaced @MockBean?
@MockitoBean and @MockitoSpyBean from Spring Framework 6.2. @MockBean still works in Boot 3.4 and 3.5 but is deprecated for removal, so new code should use the Mockito versions.
Should integration tests clean the database between tests?
Yes, or make each test create its own unique data. Shared leftover rows make tests pass or fail depending on order.

Go deeper

ShareXLinkedInWhatsApp