Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 66 ยท Testing

Testing Spring Boot Applications

Start testing Spring Boot: spring-boot-starter-test, unit tests versus @SpringBootTest, test slices, JUnit 5 with AssertJ, and the test pyramid.

A Spring Boot application is a lot of wiring: beans, configuration, a web layer, a database. Code that "looks right" can still fail at startup because of a missing bean, a wrong property name or a mapping that does not match. Tests are how you find out in seconds instead of in production, and how you keep changing the code with confidence a year from now.

The good news is that Boot makes testing easy: one starter brings everything, and the framework offers a ladder of options from "plain Java class, no Spring at all" up to "start the whole application on a random port". Choosing the right rung is the main skill, and it is what this chapter is about. Here we cover the toolbox and the strategy; the next lessons go deep on MockMvc, Testcontainers and test slices and speed. For the library-level view see Spring Boot Testing, and for the JUnit basics JUnit Basics.

Spring Boot itself cannot run on this site, so Spring test code is read-only. The TryIts run real JUnit 6 tests through the JUnit launcher, using plain Java stand-ins for the Spring parts, because the best Spring tests are exactly that: plain JUnit.

One starter, a full toolbox

Every project from Spring Initializr includes this dependency, scoped to tests only:

XML
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

It brings the libraries you will use daily:

Library Role
JUnit Jupiter The test framework: @Test, lifecycle, @ParameterizedTest
AssertJ Fluent, readable assertions: assertThat(x).isEqualTo(y)
Mockito Test doubles: mocks, stubs and verification
Spring Test and Spring Boot Test @SpringBootTest, test slices, MockMvc, property overrides
JsonPath, JSONassert Asserting on JSON documents
Awaitility Waiting for asynchronous results without Thread.sleep
Hamcrest Older matcher style, still used by MockMvc examples

In Boot 4 the starters are split into smaller modules, so a web project typically also gets a matching test starter (for example spring-boot-starter-webmvc-test). Initializr adds the right ones for your choices, and some annotation packages moved with the split, so let your IDE suggest the imports.

A ladder of tests

Plain unit test No Spring. Milliseconds.
Slice test Only the web or data layer.
Full app test @SpringBootTest, everything wired.
With real services Containers for the database or broker.

Each step is slower and more realistic. Use the lowest rung that proves the point.

1 / 2

Rung one: a plain unit test, no Spring

Your business logic should not need Spring to be tested. If a service receives its dependencies through the constructor (as you learned in IoC and Dependency Injection), a test creates it with a hand-written fake or a Mockito mock, and the test runs in a few milliseconds.

Java
class PriceServiceTest {

    @Test
    void appliesTheCustomerDiscount() {
        var customers = mock(CustomerRepository.class);
        when(customers.discountFor("ada")).thenReturn(10);

        var service = new PriceService(customers);

        assertThat(service.priceFor("ada", 2000)).isEqualTo(1800);
    }
}

There is no @SpringBootTest here, no container, no port. This is the fastest and most numerous kind of test in a healthy project. The TryIt below is the same idea with a hand-written fake instead of Mockito, run by the real JUnit launcher. The runTests helper at the bottom only exists because this page has no Maven or Gradle; in a project you press the green arrow or run mvn test.

Java A plain unit test with a fake dependency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: a JUnit test class, assertions and the launcher. What is the stand-in: the PriceService is a plain class here, whereas in a project it carries @Service; for the test it makes no difference, which is exactly the point.

Mockito in unit tests: @Mock and @InjectMocks

Hand-written fakes are fine for small interfaces, but a mock is quicker when you only need to say "when this method is called, return that" and later check "this method was called with these arguments". Mockito is on the classpath through the test starter. With its JUnit extension you declare mocks as fields and let Mockito build the object under test:

Java
@ExtendWith(MockitoExtension.class)
class PersonServiceTest {

    @Mock PersonRepository repository;           // a mock: every method returns a default (null, 0, empty)
    @Mock EmailSender emails;
    @InjectMocks PersonService service;          // built with the mocks above, by constructor first

    @Test
    void savesAndWelcomesTheNewPerson() {
        when(repository.save(any(Person.class))).thenAnswer(call -> call.getArgument(0));

        Person saved = service.register("Ada", "[email protected]");

        assertThat(saved.name()).isEqualTo("Ada");
        verify(emails).sendWelcome("[email protected]");           // was it called once, with this argument?
        verify(repository, times(1)).save(any(Person.class));
        verifyNoMoreInteractions(emails);
    }

    @Test
    void reportsAMissingPerson() {
        when(repository.findById(99L)).thenReturn(Optional.empty());

        assertThatThrownBy(() -> service.get(99L))
            .isInstanceOf(PersonNotFoundException.class);
        verify(emails, never()).sendWelcome(anyString());
    }

    @Test
    void capturesWhatWasSaved() {
        ArgumentCaptor<Person> captor = ArgumentCaptor.forClass(Person.class);

        service.register("Grace", "[email protected]");

        verify(repository).save(captor.capture());
        assertThat(captor.getValue().email()).isEqualTo("[email protected]");
    }
}

The pieces to remember:

  • @Mock creates a mock; @InjectMocks creates the real class under test and passes the mocks into its constructor (or setters, or fields). @Spy wraps a real object so you can stub some methods and keep the rest.
  • when(mock.call()).thenReturn(value) stubs a result; thenThrow(...) makes the call fail; thenAnswer(...) computes a result from the arguments. For void methods use doThrow(...).when(mock).method().
  • verify(mock).call() checks that a call happened (default: exactly once); add times(n), never(), atLeastOnce(), or InOrder for sequences. ArgumentCaptor grabs the argument for detailed assertions.
  • Matchers (any(), anyString(), eq(x)) must be used for all arguments of a call or for none. MockitoExtension runs in strict mode: an unused stub fails the test, which keeps stale setup out of your suite.
  • Inside a Spring slice or @SpringBootTest, use @MockitoBean instead so the mock replaces the real bean in the context; plain @Mock is for tests that do not start Spring at all.

Do not mock everything. Mock the boundaries of the class (repositories, clients, clocks); use real collaborators for plain value objects and pure logic, or the test only proves that you wrote the same code twice. The next TryIt builds a tiny mock with java.lang.reflect.Proxy so you can see what when, verify and @Mock do. It is a stand-in: Mockito is not on this site's Java runner, and real Mockito records calls by generating subclasses.

Java What a mock does: stubbing and verifying

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Rung two: slices

A test slice starts a part of the application context: only the beans one layer needs, with auto-configuration limited to that layer. The web slice (@WebMvcTest) loads controllers, JSON conversion and validation but no services or repositories (you supply those as mocks). The data slice (@DataJpaTest) loads entities and repositories with an in-memory database. Slices start in a second or two and check things that unit tests cannot: that the URL mapping, JSON shape, query methods and annotations really work. The next lessons cover them in detail; here is the shape of a web slice:

Java
@WebMvcTest(UserController.class)
class UserControllerTest {

    @Autowired MockMvcTester mvc;
    @MockitoBean UserService users;

    @Test
    void returnsTheUser() {
        when(users.find(1L)).thenReturn(new UserResponse(1L, "Ada"));

        assertThat(mvc.get().uri("/users/1"))
            .hasStatusOk()
            .bodyJson().extractingPath("$.name").isEqualTo("Ada");
    }
}

Rung three: @SpringBootTest

@SpringBootTest starts the whole application context: every bean, every auto-configuration, the real configuration files. It answers "does the application wire itself together, and do the layers cooperate?". By default it does not open a network port; set webEnvironment to run a real server on a random port.

Java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class OrderFlowIT {

    @Autowired TestRestTemplate rest;      // or RestTestClient in Boot 4

    @Test
    void placingAnOrderReturnsCreated() {
        var response = rest.postForEntity("/orders", new NewOrder("book-1", 2), OrderResponse.class);

        assertThat(response.getStatusCode().value()).isEqualTo(201);
        assertThat(response.getBody().quantity()).isEqualTo(2);
    }
}

Such tests are valuable but slow, because the context takes seconds to build. Spring caches contexts between test classes with the same configuration, which is why context caching matters so much for test speed. Keep a small number of full-application tests for the critical journeys and leave the details to lower rungs.

A few more annotations you will meet:

  • @MockitoBean replaces (or adds) a bean in the context with a Mockito mock. It supersedes the older @MockBean, which is gone in Boot 4.
  • @TestPropertySource and @DynamicPropertySource override properties for one test class.
  • @ActiveProfiles("test") picks a profile.
  • @TestConfiguration adds extra beans only for tests.

AssertJ: assertions that read like sentences

JUnit's own assertEquals(expected, actual) is fine, but it is easy to swap the arguments, and it grows awkward for collections and objects. AssertJ's assertThat(actual) starts from the value and chains what you expect, with failure messages that show exactly what differed:

Java
assertThat(users)
    .hasSize(2)
    .extracting(User::name)
    .containsExactly("Ada", "Grace");

assertThat(response.body())
    .startsWith("Hello")
    .doesNotContain("password");

assertThatThrownBy(() -> service.find(99L))
    .isInstanceOf(UserNotFoundException.class)
    .hasMessageContaining("99");

Use assertThat from org.assertj.core.api.Assertions and stay consistent within a project. Mixing Hamcrest, JUnit and AssertJ styles in one file makes tests harder to scan.

Reading a failing test

Test output is a conversation with your future self, so write tests that fail with a clear message. Name each test after the behaviour (rejectsPercentAboveOneHundred, not test1), keep one idea per test, and use the Arrange, Act, Assert shape. The TryIt below deliberately includes a failing test and an assertAll that reports several problems at once, so you can see what useful failure output looks like.

Java What a failing test tells you

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice what the messages give you: the expected and actual values for the plain failure, and every failed check, listed together, for the assertAll group. The order of the test lines can differ between runs, because JUnit's method order is deterministic but intentionally not obvious.

The test pyramid, applied to Boot

Put it together as a pyramid: many fast unit tests at the bottom, some slice and integration tests in the middle, few full-application and end-to-end tests at the top. The shape exists because cost grows as you climb. A unit test runs in milliseconds and points at one method when it fails; a full-application test takes seconds and may fail for a dozen unrelated reasons.

A practical split for a typical service:

  • Business rules and calculations: plain unit tests.
  • Controllers: web slice tests for status codes, JSON and validation.
  • Repositories and queries: data slice tests against a real database engine (Testcontainers when SQL dialect matters).
  • Two or three full journeys with @SpringBootTest: the application starts, the main path works, security is active.

Avoid the "ice cream cone", an inverted pyramid where almost every test starts the whole application. The suite gets slow, developers stop running it, and then it stops protecting you.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which test is the best choice for checking a discount calculation inside a service whose dependencies come through the constructor?

    Logic with injected dependencies needs no Spring at all. A plain test is the fastest and gives the most precise failures.
  2. 2. What does @WebMvcTest(UserController.class) start?

    A slice loads one layer. The web slice includes controllers, JSON conversion and validation, and you provide the service beans with @MockitoBean.
  3. 3. What is a main disadvantage of an "ice cream cone" test suite, where most tests are full @SpringBootTest tests?

    Full-context tests are costly and fail for many reasons. A suite like that becomes slow and noisy, which erodes trust in it.
  4. 4. Why do many teams prefer AssertJ's assertThat(actual)... over assertEquals(expected, actual)?

    AssertJ starts from the actual value and chains expectations, with rich messages for collections and objects. It does not replace JUnit; it replaces its assertion methods.

Summary

  • spring-boot-starter-test brings JUnit, AssertJ, Mockito, Spring Test, JsonPath and Awaitility in one test-scoped dependency.
  • Prefer plain unit tests for logic: constructor injection makes them trivial and fast.
  • Slices (@WebMvcTest, @DataJpaTest, and others) start only one layer and verify wiring and mappings.
  • @SpringBootTest starts everything; keep a few for critical journeys because contexts are expensive.
  • @MockitoBean replaces a bean with a mock; @DynamicPropertySource and @ActiveProfiles adjust configuration.
  • Write behaviour-named tests with clear failure messages, and shape the suite like a pyramid.

Next: Testing Controllers with MockMvc.