Sub topic 14
Testing beans with and without the container
This chapter assumes you know constructor injection, @Configuration and @Bean, and basic JUnit 5. The goal is to decide when a test needs Spring and when plain Java is enough.
Start without the container
A bean is an ordinary object. If it takes its dependencies through the constructor, you can build it with new and hand it a fake. This is the main practical payoff of constructor injection.
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);
}
}MessageSender has one method, so a lambda works as the fake. The test needs no annotations from Spring, no ApplicationContext and no classpath scanning. It runs in milliseconds and fails only when NotificationService behaves differently.
Field injection makes this harder. A private @Autowired field has no constructor parameter and no setter, so a test must use reflection or start the container. That is one reason to prefer constructor injection.
Test with the container when wiring is the thing under test
A unit test cannot catch a missing @Bean, an ambiguous MessageSender, a wrong @Qualifier or a misspelled property. For those, load a real ApplicationContext. The spring-test module provides @SpringJUnitConfig, which builds a context from the classes you list and injects beans into the test.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
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(NotificationServiceWiringTest.TestConfig.class)
class NotificationServiceWiringTest {
static final List<String> SENT = new ArrayList<>();
@Configuration
static class TestConfig {
@Bean
MessageSender sender() {
return (to, body) -> SENT.add(to + ":" + body);
}
@Bean
NotificationService notificationService(MessageSender sender) {
return new NotificationService(sender);
}
}
@Autowired
NotificationService service;
@BeforeEach
void clear() {
SENT.clear();
}
@Test
void containerWiresTheFakeSender() {
service.welcome("ana");
assertEquals(List.of("ana:Welcome!"), SENT);
}
}The test configuration replaces the production emailSender with a fake. This shows a general technique: build a small configuration that contains only the beans the test needs, and swap real collaborators (mail servers, databases) for fakes.
Spring caches a context between test classes that use the same configuration. Reusing configurations keeps a large suite fast.
Choosing a test style
| Question | Plain unit test | Container test |
|---|---|---|
| Speed | Milliseconds | Slower, depends on context size |
| Catches missing or ambiguous beans | No | Yes |
| Catches business logic errors | Yes | Yes, but harder to pinpoint |
| Needs `spring-test` | No | Yes |
Common mistakes
- Starting the full application for every test. A narrow configuration is faster and fails with clearer messages.
- Sharing mutable state between tests, as the static
SENTlist does here. Clear it before each test, asclear()does. - Mocking so much that the test only checks the mocks. Prefer a simple fake when the behavior is easy to write by hand.
Exercise
Why can NotificationService be tested with new, and what kind of defect still needs a container test?
Show answer
It takes MessageSender through its constructor, so a test can pass a fake directly with no Spring involved. Defects in wiring need a container test. Examples are a missing @Bean, two candidates for one type without @Primary or @Qualifier, or a wrong profile, because only a real ApplicationContext resolves those.