Sub topic 2
Profiles, Test Properties, and Focused Spring Boot Tests
This chapter assumes Java, JUnit 5, dependency injection, and basic Spring Boot testing. Choose the smallest test that proves the behavior you need.
Profiles, test properties, and `@TestConfiguration`
A profile selects environment-specific beans and settings. Activate a test profile with @ActiveProfiles:
@SpringBootTest
@ActiveProfiles("test")
class GreetingApplicationTest {
}Test-specific values can be supplied directly:
@SpringBootTest(properties = "greeting.prefix=Test")
class GreetingServiceTest {
}For reusable test beans, use @TestConfiguration. It adds configuration for tests without changing the application’s production configuration.
@TestConfiguration
class FakeClockConfiguration {
@Bean
Clock clock() {
return Clock.fixed(
Instant.parse("2026-01-01T00:00:00Z"),
ZoneOffset.UTC);
}
}Import it with @Import(FakeClockConfiguration.class).
Replacing beans with mocks
A mock is an object with programmed behavior that records how it was used. In a Spring test, @MockitoBean replaces a bean in the application context with a Mockito mock. In Spring Boot versions before 3.4, use @MockBean.
@SpringBootTest
class GreetingServiceContextTest {
@MockitoBean
GreetingRepository repository;
@Autowired
GreetingService service;
}Use this when the test needs Spring wiring but should isolate one collaborator.
Test slices: loading only what you need
A test slice loads part of the application instead of the whole context. It starts faster and makes the test’s boundary clear.
Testing controllers with `@WebMvcTest` and `MockMvc`
@WebMvcTest loads MVC components, including the controller under test. MockMvc sends requests without starting a real server.
@WebMvcTest(GreetingController.class)
class GreetingControllerTest {
@Autowired MockMvc mvc;
@MockitoBean GreetingService service;
@Test
void returnsGreeting() throws Exception {
when(service.greetingFor("Ada")).thenReturn("Hello, Ada");
mvc.perform(get("/greetings/Ada"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, Ada"));
}
}Testing repositories with `@DataJpaTest`
@DataJpaTest configures entities, repositories, and JPA. Tests usually run in a rollback transaction and use an embedded database when one is available.
@DataJpaTest
class GreetingRepositoryTest {
@Autowired GreetingRepository repository;
@Test
void findsGreetingByName() {
repository.save(new Greeting("Ada", "Hello, Ada"));
assertThat(repository.findByName("Ada")).isPresent();
}
}Use Testcontainers instead when database-specific behavior matters.
Exercise
Which annotation should you choose to test request mapping while mocking the service?
Show answer
Use @WebMvcTest with MockMvc and a @MockitoBean service.