Test Overview
This test starts the full Spring Boot application context and verifies that the main service bean is loaded correctly.
This test starts the full Spring Boot application context and verifies that the main service bean is loaded correctly.
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import static org.junit.jupiter.api.Assertions.assertNotNull; @SpringBootTest public class ApplicationContextTest { @Autowired private MyService myService; @Test public void contextLoads() { assertNotNull(myService, "MyService bean should be loaded in the context"); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initializes | — | PASS |
| 2 | Spring Boot application context loads with @SpringBootTest | Full Spring context with all beans is created | — | PASS |
| 3 | JUnit injects MyService bean into test class | myService field is assigned a valid bean instance | — | PASS |
| 4 | Test method contextLoads() runs and asserts myService is not null | myService is a valid bean instance | assertNotNull(myService) | PASS |
| 5 | Test finishes successfully | Test runner reports success | — | PASS |
@SpringBootTest in a test class?@SpringBootTest does@SpringBootTest is used for integration tests to check how components work together.@SpringBootTest = full app context [OK]@RunWith(SpringRunner.class) and @SpringBootTest.@RunWith(SpringRunner.class) with @SpringBootTest [OK]\@SpringBootTest
class MyServiceTest {
\@Autowired
private MyService myService;
\@Test
void testService() {
assertNotNull(myService);
System.out.println("Service is loaded");
}
}@SpringBootTest does heremyService bean is injected and not null.assertNotNull(myService) passes, and the print statement outputs "Service is loaded".@SpringBootTest but it fails with a NoSuchBeanDefinitionException. What is the most likely cause?NoSuchBeanDefinitionException means Spring could not find a bean of the required type in the context.@SpringBootTest to limit the loaded beans?classes attribute in @SpringBootTest, you can load only selected configuration classes, reducing context size.@SpringBootTest disables context loading, @MockBean mocks beans but does not limit context size, and @Transactional controls transactions, not context loading.@SpringBootTest(classes = YourConfig.class) to load only specific configuration -> Option BPass the test and this pattern moves unknown