Sub topic 2
What spring-boot-starter-test gives you
This chapter covers the single test dependency that most Spring Boot projects use. It lists what the dependency brings in, how Gradle and Maven wire it up, and which common mistakes it causes. It assumes you can build a simple Spring Boot application with Maven or Gradle, you know what a Spring bean is, and you have written a basic JUnit test.
One dependency, many libraries
Spring Boot does not ask you to pick and version each test library yourself. It ships one starter, spring-boot-starter-test, that pulls in a set of libraries whose versions are known to work together. The Spring Boot dependency management fixes those versions, so you declare the starter and nothing else.
The starter brings in these libraries:
| Library | Role in your tests |
|---|---|
| JUnit Jupiter (JUnit 5) | The test engine and the annotations such as `@Test`, `@BeforeEach`, and `@ParameterizedTest`. |
| AssertJ | Fluent assertions such as `assertThat(x).isEqualTo(y)`. |
| Mockito | Mock objects and stubbing with `when(...).thenReturn(...)`. |
| Spring Test | `MockMvc`, the `TestContext` framework, and `@ContextConfiguration`. |
| Spring Boot Test | `@SpringBootTest`, the test slices, `TestRestTemplate`, and `@MockitoBean` support. |
| Spring Boot Test Autoconfigure | The auto-configuration behind slices such as `@WebMvcTest` and `@DataJpaTest`. |
| JSONassert | Comparing JSON documents, including lenient comparison. |
| JsonPath | Reading values from JSON with path expressions. |
| Awaitility | Waiting for asynchronous results without fixed sleeps. |
| Hamcrest | Matcher library that `MockMvc` result matchers and some older assertions use. |
| XMLUnit | Comparing XML documents. |
You will not use all of these in every test. Most tests touch only JUnit, AssertJ, and Mockito. The rest appear when you test web layers, JSON, or asynchronous code.
Adding the starter
In Gradle, declare the starter with the testImplementation configuration. Then tell Gradle to run tests on the JUnit Platform.
dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}testImplementation keeps the libraries off your production classpath. They are available when Gradle compiles and runs tests only. The useJUnitPlatform() call matters. Without it, Gradle's default test task looks for JUnit 4 style tests and silently finds none of your JUnit 5 tests. The build then reports success with zero tests run.
In Maven, the equivalent uses test scope:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>Maven's Surefire plugin detects JUnit 5 on its own, so there is no extra setting.
If you generate a project with Spring Initializr, the starter is already in the build file. You only need to add it by hand in a project that did not start from Initializr.
Checking what you actually have
When a test fails to compile because an annotation or class is missing, look at the dependency tree before guessing. In Gradle, run this:
./gradlew dependencies --configuration testRuntimeClasspathIn Maven, run this:
./mvnw dependency:tree -Dscope=testThe output shows each library and its version. It also shows which libraries are missing. That second part matters, because the starter does not include everything you may want.
What the starter does not include
Several things that tests often need live elsewhere. Knowing the gaps saves time when a class cannot be found.
- Spring Security test support.
@WithMockUserand theSecurityMockMvcRequestPostProcessorshelpers come fromspring-security-test. Add it separately when your application uses Spring Security. - Testcontainers. Real databases in containers need
org.testcontainers:junit-jupiterand a module such asorg.testcontainers:postgresql. For@ServiceConnection, you also needspring-boot-testcontainerson the test classpath. - A database driver and an embedded database.
@DataJpaTestneeds a JDBC driver for whatever database it talks to. If you rely on the default embedded database, you need H2, HSQLDB, or Derby on the test classpath. - Actuator. A test that calls
/actuator/healthneedsspring-boot-starter-actuatoron the classpath. Later chapters use that endpoint as a simple full-stack check. - Web and JPA starters. The test starter does not bring in
spring-boot-starter-weborspring-boot-starter-data-jpa. A web-layer test works only if the application itself already depends on the web starter.
The pattern is simple. The test starter supplies the test tools. Your application dependencies supply the code under test.
How the libraries divide the work
Each library has a clear job, and the jobs do not overlap much. Keeping them separate in your head helps you read test code.
- JUnit Jupiter runs the test. It finds methods, creates the test instance, calls lifecycle methods, and reports results.
- Mockito creates stand-ins for collaborators. A stand-in is a mock, and you tell it what to return.
- AssertJ checks results after the call.
- Spring Test and Spring Boot Test connect all of that to a Spring application context when you need one.
The next code block shows the first three working together without any Spring context. It is a complete test class with its imports.
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
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;
@ExtendWith(MockitoExtension.class)
class GreetingServiceTest {
@Mock
GreetingRepository repository;
@InjectMocks
GreetingService service;
@Test
void returnsStoredGreeting() {
when(repository.findByName("Ada"))
.thenReturn(Optional.of(new Greeting("Ada", "Hello, Ada")));
assertThat(service.greetingFor("Ada")).isEqualTo("Hello, Ada");
}
}GreetingRepository, GreetingService, and Greeting are the application classes from the earlier chapters. This test starts no Spring context, so it finishes in milliseconds. The starter made it possible, but Spring itself is not involved. Chapter 3 returns to this style in detail.
Two ways to use Spring in a test
Spring Boot Test adds two kinds of context-aware tests on top of the plain libraries.
- Full-context tests use
@SpringBootTest. They load the whole application context, the same way a real run does. - Slice tests use annotations such as
@WebMvcTestand@DataJpaTest. They load only the beans for one layer.
Both kinds depend on the starter. The annotations, MockMvc, TestRestTemplate, and the mock bean support are all in the Spring Boot Test and Spring Test jars. Later chapters cover when to choose each kind.
Common problems and how to read them
No tests run, build succeeds. In Gradle, useJUnitPlatform() is missing. Add it to the test task.
Tests written with org.junit.Test do not run. The starter supplies JUnit 5 only. The org.junit.Test annotation belongs to JUnit 4, and the JUnit 5 engine ignores it. Use org.junit.jupiter.api.Test. If you must keep old JUnit 4 tests, you need the junit-vintage-engine dependency, which the starter no longer brings in.
A mock field stays null. @Mock and @InjectMocks only work when MockitoExtension is active. Add @ExtendWith(MockitoExtension.class) to a plain unit test. Inside a Spring context test, use @MockitoBean instead, which a later chapter covers.
Strict stubbing errors. MockitoExtension uses strict stubs by default. If you stub a call that the test never makes, Mockito fails the test with UnnecessaryStubbingException. Remove the unused stub instead of loosening the check, because an unused stub often points to a test that does not exercise what you think it does.
Wrong assertThat imported. Your IDE may offer assertThat from Hamcrest, JUnit 4, or AssertJ. Hamcrest's version takes a matcher as a second argument. AssertJ's version chains methods. Use the static import from org.assertj.core.api.Assertions for fluent checks.
Missing class for @WithMockUser or @ServiceConnection. These come from other artifacts, as the earlier list shows. Add the missing artifact with test scope.
Choosing extra test dependencies
Add libraries to the starter only when a test needs them, and add them in test scope. A quick way to decide:
| You want to test | Extra dependency to consider |
|---|---|
| Secured endpoints | `spring-security-test` |
| A real PostgreSQL, MySQL, or similar database | `org.testcontainers:junit-jupiter`, a database module, and `spring-boot-testcontainers` |
| Actuator endpoints | `spring-boot-starter-actuator` |
| Fast repository tests with no container | An embedded database such as H2 |
| Legacy JUnit 4 tests | `junit-vintage-engine` |
An embedded database is faster to start than a container, but it can behave differently from your production database. A later chapter explains that trade-off and why this tutorial favors a real database for repository tests.
Exercise
A Gradle project has testImplementation 'org.springframework.boot:spring-boot-starter-test' in its dependencies, and you write a test class with @Test imported from org.junit.jupiter.api. ./gradlew build succeeds, but the report shows zero tests executed. What is the most likely cause, and what is the fix? Then name one artifact you would add so the same project can use @WithMockUser in tests.
Show answer
The test task is not configured to use the JUnit Platform. Add tasks.named('test') { useJUnitPlatform() } to the build file so Gradle discovers JUnit 5 tests. For @WithMockUser, add testImplementation 'org.springframework.security:spring-security-test', because the starter does not include Spring Security test support.
Exercise
Your team lead asks you to add org.mockito:mockito-core:4.0.0 with an explicit version next to the starter "to be safe". Give one reason to avoid this, and the command that shows which Mockito version the starter already provides.
Show answer
Spring Boot's dependency management already picks a Mockito version that works with the other libraries in the starter, so a hand-pinned version can create incompatibilities that appear as runtime errors. Run ./gradlew dependencies --configuration testRuntimeClasspath (Gradle) or ./mvnw dependency:tree -Dscope=test (Maven) to see the managed Mockito version.