Sub topic 1
What to test and at which level
Prerequisites
This chapter assumes Java basics, JUnit-style tests, dependency injection, Spring beans, and basic Maven or Gradle use. You should also know how a Spring Boot application exposes REST controllers and persists data with Spring Data JPA.
Choose the cheapest useful test
Test each behavior at the lowest level that can prove it works. A unit test checks one class without starting Spring. A slice test starts selected Spring infrastructure, such as MVC or JPA. A full-context test starts the application and checks how its parts work together.
| Test level | Best for | Speed |
|---|---|---|
| Unit | Service rules and calculations | Fast |
| Slice | Controllers or repositories | Medium |
| Full context | Wiring and end-to-end behavior | Slow |
What the test starter provides
spring-boot-starter-test is a dependency bundle. It normally provides JUnit Jupiter for test execution, Mockito for test doubles, AssertJ for readable assertions, and Spring Test support.
With Gradle, enable the JUnit Platform:
dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}Unit testing a service
A unit test creates the service directly. Mockito supplies a mock, which is an object controlled by the test. AssertJ checks the result.
@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");
}
}This test does not prove that Spring discovered the repository or configured a database. It proves the service behavior for the configured repository response.
Loading the context with `@SpringBootTest`
@SpringBootTest loads the application context, which is Spring’s registry of configured beans. Use it when bean wiring, configuration, or several layers must work together. It costs more time than a unit test.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class GreetingApiTest {
@Autowired TestRestTemplate restTemplate;
@Test
void healthEndpointIsUp() {
assertThat(restTemplate.getForEntity(
"/actuator/health", String.class
).getStatusCode()).isEqualTo(HttpStatus.OK);
}
}Exercise
Which test level should verify a service’s branching rule when its repository can be mocked?
Show answer
Use a unit test. It avoids the Spring context and gives fast, focused feedback.