Sub topic 14
Testing beans with and without the container
This chapter covers how to test Spring beans. It shows when a plain unit test is enough and when you need a Spring container. It assumes you can write JUnit 5 tests and have read the earlier chapters on injection styles, @Configuration and @Bean, and profiles. Examples use Spring Framework 6, Spring Boot 3 and Mockito.
Why the injection style decides how you test
Dependency injection exists partly to make code testable. A bean that declares its dependencies as constructor parameters can be created with new in a test. The test supplies whatever implementation it likes, so no container is involved.
The unit test below uses the NotificationService from earlier in the tutorial. It passes a lambda as a fake MessageSender and records what the service sends.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
class NotificationServiceTest {
@Test
void welcomeSendsMessage() {
List<String> sent = new ArrayList<>();
NotificationService service =
new NotificationService((to, body) -> sent.add(to + ":" + body));
service.welcome("ana");
assertEquals(List.of("ana:Welcome!"), sent);
}
}This test has no @SpringBootTest, no context startup and no classpath scanning. It runs in milliseconds, and a failure points at your code, not at wiring.
What goes wrong with field injection
Field injection hides the dependency from the constructor. Here is the same service written that way:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class LegacyNotificationService {
@Autowired
private MessageSender sender;
public void welcome(String user) {
sender.send(user, "Welcome!");
}
}new LegacyNotificationService().welcome("ana") throws a NullPointerException, because only the container sets the private field. To test this class you must either start a context or use reflection (for example Mockito's @InjectMocks). Both approaches work, but the first is slow and the second depends on Mockito's field-matching rules. Constructor injection also makes the dependency list visible, so a class with eight constructor parameters shows its size problem right away.
Unit tests with Mockito
A hand-written fake is fine for small interfaces. When you need to check that a call happened, or to stub return values, use a Mockito mock. It is still a plain unit test, and the container plays no part.
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.junit.jupiter.api.Test;
class NotificationServiceMockTest {
@Test
void welcomeCallsSenderOnce() {
MessageSender sender = mock(MessageSender.class);
NotificationService service = new NotificationService(sender);
service.welcome("ana");
verify(sender).send("ana", "Welcome!");
}
}Choose between fakes and mocks like this:
- A fake (a small working implementation) suits state-based checks, such as "the list contains this message". It survives refactoring better, because it doesn't care how many times a method was called.
- A mock suits interaction checks, such as "
sendwas called with these arguments". Over-specifiedverifycalls make tests brittle, so verify only the interactions that matter.
When you do need the container
A unit test cannot tell you whether your wiring is correct. These problems appear only when a real ApplicationContext is built:
- A missing
@Beanmethod or a class outside the scanned packages. - Two candidates for one type with no
@Primaryor@Qualifier. - A profile or
@Conditionalthat selects the wrong bean. - A
@ConfigurationPropertiesbinding with a wrong prefix or property name. - Lifecycle callbacks such as
@PostConstructthat must run. - Behavior added by proxies, such as
@Transactionalor@Async.
The Spring TestContext Framework builds a context for a test class and injects beans into the test instance. @SpringJUnitConfig combines JUnit 5 support with a context configuration.
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig(AppConfig.class)
class AppConfigWiringTest {
@Autowired
NotificationService service;
@Test
void contextWiresNotificationService() {
assertNotNull(service);
}
}If AppConfig is broken, this test fails with the same UnsatisfiedDependencyException or NoSuchBeanDefinitionException you would see at application startup. Such a test is a cheap safety net, and it is worth having one per major configuration class.
Replacing beans in a container test
Container tests often need one real wiring with one piece swapped out, such as a sender that records messages instead of calling an email server. There are three common ways to do that.
A test-only configuration class
For a plain Spring test, point the context at a nested @Configuration class that defines the beans the test needs.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig(RecordingSenderTest.TestConfig.class)
class RecordingSenderTest {
static class RecordingSender implements MessageSender {
final List<String> sent = new ArrayList<>();
@Override
public void send(String to, String body) {
sent.add(to + ":" + body);
}
}
@Configuration
static class TestConfig {
@Bean
RecordingSender recordingSender() {
return new RecordingSender();
}
@Bean
NotificationService notificationService(MessageSender sender) {
return new NotificationService(sender);
}
}
@Autowired
NotificationService service;
@Autowired
RecordingSender sender;
@Test
void messageIsRecorded() {
service.welcome("ana");
assertEquals(List.of("ana:Welcome!"), sender.sent);
}
}Both beans share one container, so the RecordingSender injected into the test is the same instance the service uses. This works because singleton scope is the default.
Bean overrides in Spring Boot tests
In a Spring Boot application, @SpringBootTest starts the full application context. Annotate a field with @MockitoBean to replace the bean of that type with a Mockito mock.
import static org.mockito.Mockito.verify;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
@SpringBootTest
class BootWiringTest {
@MockitoBean
MessageSender sender;
@Autowired
NotificationService service;
@Test
void serviceUsesTheMock() {
service.welcome("ana");
verify(sender).send("ana", "Welcome!");
}
}This example assumes the application has exactly one MessageSender bean. With several candidates, override by name or add a qualifier, or you get the ambiguity errors from the autowiring chapter. @MockitoBean comes from Spring Framework 6.2. Older Boot 3 code uses @MockBean, which newer Boot versions deprecate.
Test properties and profiles
Two annotations control environment-dependent beans without editing production files:
@ActiveProfiles("test")activates thetestprofile, so beans marked@Profile("test")register and production-only beans do not.@TestPropertySource(properties = "mail.host=localhost")supplies property values that@Valueand@ConfigurationPropertiesread.
Choosing the test type
Use this order of preference: start with a plain unit test and move to a container test only when the thing under test is the wiring.
| Aspect | Plain unit test | Container test |
|---|---|---|
| Startup cost | None | Builds a context, from tens of milliseconds to many seconds |
| What a failure means | Logic bug in the bean | Logic bug or wiring or configuration bug |
| Dependencies | Passed to the constructor | Resolved by the container |
| Proxies such as `@Transactional` | Not applied | Applied |
| Typical count | Many | Few |
Edge cases and common mistakes
Context caching
The TestContext Framework caches contexts. Test classes with an identical configuration (same classes, profiles, properties and bean overrides) share one context. Two consequences follow:
- Each distinct combination of
@MockitoBeanfields, properties or profiles creates a new context. A suite that varies these in every class loses most of the speedup. - Singleton state leaks between test classes that share a context. A
RecordingSenderthat is never cleared keeps messages from earlier tests. Reset state in@BeforeEach, or avoid mutable singletons.
@DirtiesContext discards the cached context after a test or class. It is a last resort, because it forces a rebuild.
Mocks are not reset by magic
@MockitoBean mocks reset after each test method. A hand-built mock stored in a singleton @Bean does not. If you register mock(MessageSender.class) from a test configuration, call Mockito.reset(...) yourself.
Do not test the container itself
A test that only asserts ctx.getBean(X.class) != null for every class duplicates what Spring already guarantees. Test a configuration class when it contains decisions, such as conditions, profiles, or @Primary choices. One smoke test that loads the real context is usually enough for the rest.
Constructor visibility
If a test needs to call a package-private constructor, put the test in the same package. Don't make the constructor public only for tests, and don't reach for field injection.
Exercise
A teammate writes new ReportService() in a test, where ReportService has @Autowired private ReportRepository repository;, and the test fails with a NullPointerException. Give two ways to fix the test and the change that makes the problem go away for good.
Show answer
The new call bypasses the container, so the private field is never set. Fix 1: build a Spring context (for example @SpringJUnitConfig or @SpringBootTest) and autowire ReportService into the test. Fix 2: keep new but inject the repository through reflection, for example with Mockito's @InjectMocks. The lasting fix is to switch ReportService to constructor injection. Tests can then call new ReportService(fakeRepository) with no container and no reflection.
Exercise
Your suite has 40 @SpringBootTest classes and takes ten minutes. Most of them use different @MockitoBean fields or @TestPropertySource values. Why is it slow, and what would you change?
Show answer
Each distinct combination of configuration, properties, profiles and bean overrides produces a separate cached context, so the suite builds many contexts instead of reusing a few. To speed it up, move logic checks to plain unit tests with constructor-injected fakes. Keep only a few container tests. Make the remaining ones share one configuration by using the same overrides and properties, and remove @DirtiesContext unless a test really changes shared state.