Testing with Spring

Key idea
Spring's *TestContext framework* manages the `ApplicationContext` of integration tests: it creates it from the configuration you declare, injects beans into the test class, **caches** it to reuse it across classes with the same configuration and applies transactions, SQL scripts, profiles and properties through annotations.
In the box
Every test of the box leaderboard built its own Spring context by hand. Tell unit tests from integration tests, let Spring's TestContext create, inject and cache the context, and control profiles, properties, SQL data and rollback with annotations.
JUnit 5new …ApplicationContext()

JUnit calls a hand-built context, highlighted in red, which is built, started and closed in every test.

JUnit calls podium("Fran") on LeaderboardService, which queries a ResultRepository mock; both are highlighted and there's no Spring context.

JUnit passes @SpringJUnitConfig to the SpringExtension, which asks the TestContextManager to prepare the test; both are highlighted.

The context cache, highlighted, returns context #1 already created: same key, it's reused.

Context #2 appears, highlighted: after @DirtiesContext, the cache creates a new one.

The TestContextManager sends the cache, highlighted, the key made of classes, profiles and properties.

The fran-results.sql script, highlighted, inserts data into context #1 and, when the test ends, a ROLLBACK happens.

The TestContextManager, highlighted, receives the configuration from a static class nested in the test itself.

Final view: JUnit, the SpringExtension, the TestContextManager and the cache with its two contexts; below, the unit test with its mock and the SQL script.

Step 1 of 9

A hand-built context in every test

ManualContextTest tests the box leaderboard like this:

  1. It creates an AnnotationConfigApplicationContext by hand.
  2. It activates the profile, registers the configuration and starts it.
  3. It looks up the service with getBean.
  4. It closes it at the end.

It works, but it's repeated in every test and, above all, starts a new context every time. With hundreds of tests, the time explodes.

Step 2 of 9

First: do you need Spring?

Not every test needs a context. LeaderboardServiceUnitTest tests LeaderboardService in isolation:

  • The repository is a Mockito mock: mock(ResultRepository.class).
  • when(...).thenReturn(...) prepares answers; verify(..., never()) checks interactions.
  • new LeaderboardService(mock, clock, 3): plain Java, milliseconds.

Thanks to constructor injection, the class is tested without Spring. That's a unit test. An integration test checks several real pieces fit together: configuration, database, transactions. For that you do need Spring.

Step 3 of 9

@SpringJUnitConfig and the SpringExtension

For integration tests, Spring's TestContext framework does the work:

  • @ExtendWith(SpringExtension.class) connects Spring with JUnit 5.
  • @ContextConfiguration(classes = LeaderboardConfig.class) says which configuration to load.
  • @SpringJUnitConfig(LeaderboardConfig.class) combines both.

The TestContextManager creates the context (or takes it from the cache) and injects whatever you ask for with @Autowired into the test class, as in any bean.

Step 4 of 9

The context cache

Starting a context is expensive, so the framework caches them (in memory, for the whole test JVM run):

  • The key is the full configuration: classes, active profiles, test properties, initializers, customizers…
  • Another test class with the same key gets the same context, already started.

FirstCachedTest and SecondCachedTest use the same configuration. A bean counts how many times it was created and both tests see 1.

Step 5 of 9

@DirtiesContext: throwing the context away

If a test modifies the context's state (a singleton holding data, a changed property…), the next ones could be affected. @DirtiesContext marks the context as dirty: it's closed and removed from the cache, and the next test gets a new one.

In DirtiesContextTest, the first method writes to a shared bean and carries @DirtiesContext; the second gets an empty bean and the context counter is 2.

It goes on the class or the method, and you choose when (classMode, methodMode: before or after).

Step 6 of 9

@ActiveProfiles and @TestPropertySource

Two annotations to tune the test context:

  • @ActiveProfiles("test"): activates profiles. Here it picks the fixed clock (@Profile("test")), so the title doesn't depend on today's date.
  • @TestPropertySource(properties = "leaderboard.size=2"): adds properties with the highest priority. It also takes locations = "classpath:test.properties".

Both are part of the cache key: a test with other profiles or properties uses another context.

Step 7 of 9

@Sql and rollback

To prepare data, @Sql("/fran-results.sql") runs a script before the method (with executionPhase = AFTER_TEST_METHOD, after).

With @Transactional on the test, the script and everything the test does go in a transaction that is rolled back at the end. That's why the second test finds the table empty.

Step 8 of 9

Nested configuration

DirtiesContextTest carries @SpringJUnitConfig with no classes. Where does the configuration come from?

From the static nested class annotated with @Configuration. If @ContextConfiguration names neither classes nor locations, Spring looks for nested configurations in the test class. Handy for tests with a small configuration of their own.

Step 9 of 9

Recap

  • Unit (Mockito, no Spring) versus integration (real context).
  • @SpringJUnitConfig = SpringExtension + @ContextConfiguration; beans are injected into the test.
  • Context cache by key (classes, profiles, properties…); @DirtiesContext invalidates it.
  • @ActiveProfiles, @TestPropertySource (highest priority).
  • @Sql + @Transactional → prepared data and rollback.
  • No classes: static nested configuration.

Cheatsheet →

Code

ManualContextTest.java

@Test
void eachTestBuildsAndTearsDownItsOwnContext() {
    try (var ctx = new AnnotationConfigApplicationContext()) {   // built by hand…
        ctx.getEnvironment().setActiveProfiles("test");
        ctx.register(LeaderboardConfig.class);
        ctx.refresh();                                          // …started (slow)…
        LeaderboardService service = ctx.getBean(LeaderboardService.class); // …looked up by hand

        assertThat(service.podium("Fran")).isEmpty();
    }                                                           // …and thrown away
}

LeaderboardServiceUnitTest.java

class LeaderboardServiceUnitTest {          // no Spring at all: milliseconds
    ResultRepository results = mock(ResultRepository.class);  // a Mockito mock instead of the database
    LeaderboardService service = new LeaderboardService(results, Clock.systemUTC(), 3);

    @Test
    void thePodiumComesFromTheRepository() {
        when(results.fastest("Fran", 3)).thenReturn(List.of("Ana", "Leo"));

        assertThat(service.podium("Fran")).containsExactly("Ana", "Leo");
    }

    @Test
    void invalidTimesNeverReachTheRepository() {
        assertThatThrownBy(() -> service.record("Ana", "Fran", 0)).isInstanceOf(IllegalArgumentException.class);
        verify(results, never()).save(anyString(), anyString(), anyInt());
    }
}

LeaderboardIntegrationTest.java

@SpringJUnitConfig(LeaderboardConfig.class)  // = @ExtendWith(SpringExtension.class) + @ContextConfiguration
@ActiveProfiles("test")                      // activates the fixed clock
@TestPropertySource(properties = "leaderboard.size=2") // highest-priority properties for this test
class LeaderboardIntegrationTest {
    @Autowired
    LeaderboardService leaderboard;          // beans injected into the test instance
    // …
}

FirstCachedTest.java

@SpringJUnitConfig(CacheDemoConfig.class)
class FirstCachedTest {
    @Test
    void theContextIsCreatedOnce() {
        assertThat(ContextCounter.CREATED).hasValue(1);
    }
}

// SecondCachedTest has the same configuration (same classes, profiles, properties…),
// so the TestContext framework hands it the SAME cached context: the counter is still 1.

DirtiesContextTest.java

@SpringJUnitConfig
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class DirtiesContextTest {
    static final AtomicInteger CONTEXTS = new AtomicInteger();

    @Configuration                       // nested static @Configuration: detected automatically
    static class Config {
        @Bean
        StringBuilder board() {
            CONTEXTS.incrementAndGet();
            return new StringBuilder();
        }
    }

    @Autowired StringBuilder board;

    @Test @Order(1)
    @DirtiesContext                      // "I broke the shared state": close this context afterwards
    void scribblesOnTheSharedBoard() {
        board.append("Fran 3:51");
        assertThat(CONTEXTS).hasValue(1);
    }

    @Test @Order(2)
    void getsAFreshContext() {
        assertThat(board.toString()).isEmpty(); // a brand-new bean
        assertThat(CONTEXTS).hasValue(2);
    }
}

LeaderboardIntegrationTest.java

@SpringJUnitConfig(LeaderboardConfig.class)  // = @ExtendWith(SpringExtension.class) + @ContextConfiguration
@ActiveProfiles("test")                      // activates the fixed clock
@TestPropertySource(properties = "leaderboard.size=2") // highest-priority properties for this test
class LeaderboardIntegrationTest {
    @Autowired
    LeaderboardService leaderboard;          // beans injected into the test instance
    // …
}

LeaderboardIntegrationTest.java

@Test
@Sql("/fran-results.sql")                // runs before the test method…
@Transactional                           // …inside the test transaction, rolled back afterwards
void thePodiumHasTheConfiguredSize() {
    assertThat(leaderboard.podium("Fran")).containsExactly("Ana", "Leo"); // size 2 from the property
}

@Test
@Transactional
void eachTestStartsClean() {
    assertThat(leaderboard.podium("Fran")).isEmpty();  // the previous inserts were rolled back
}

DirtiesContextTest.java

@SpringJUnitConfig
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class DirtiesContextTest {
    static final AtomicInteger CONTEXTS = new AtomicInteger();

    @Configuration                       // nested static @Configuration: detected automatically
    static class Config {
        @Bean
        StringBuilder board() {
            CONTEXTS.incrementAndGet();
            return new StringBuilder();
        }
    }

    @Autowired StringBuilder board;

    @Test @Order(1)
    @DirtiesContext                      // "I broke the shared state": close this context afterwards
    void scribblesOnTheSharedBoard() {
        board.append("Fran 3:51");
        assertThat(CONTEXTS).hasValue(1);
    }

    @Test @Order(2)
    void getsAFreshContext() {
        assertThat(board.toString()).isEmpty(); // a brand-new bean
        assertThat(CONTEXTS).hasValue(2);
    }
}

LeaderboardIntegrationTest.java

@SpringJUnitConfig(LeaderboardConfig.class)  // = @ExtendWith(SpringExtension.class) + @ContextConfiguration
@ActiveProfiles("test")                      // activates the fixed clock
@TestPropertySource(properties = "leaderboard.size=2") // highest-priority properties for this test
class LeaderboardIntegrationTest {
    @Autowired
    LeaderboardService leaderboard;          // beans injected into the test instance
    // …
}

Quiz

1. What is @SpringJUnitConfig(LeaderboardConfig.class)?

2. Two test classes use exactly the same configuration, profiles and properties. How many contexts does Spring create?

3. What is @DirtiesContext for?

4. A test method carries @Sql("/fran-results.sql") and @Transactional. What happens to the rows the script inserted when the test ends?

5. What characterizes a unit test compared with an integration test?

6. A test class uses @SpringJUnitConfig with no classes. Where does Spring get the configuration from?

Cheatsheet → · Mock exam →

Run it