Verify Spring Boot Application Context Loads Successfully
Preconditions (3)
✅ Expected Result: The test passes if the Spring application context loads successfully without any exceptions or errors
package com.example.demo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class DemoApplicationTests { @Test void contextLoads() { // This test will pass if the application context loads successfully } }
The test class is annotated with @SpringBootTest to tell Spring Boot to load the full application context for testing.
The test method contextLoads() is annotated with @Test from JUnit Jupiter. It is empty because the test will automatically fail if the context fails to load.
This simple test ensures that the Spring Boot application starts up correctly without any configuration or bean errors.
Add a test that verifies a specific Spring bean is loaded in the application context
@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