What is the main benefit of writing tests for a Spring Boot application?
Think about how testing helps developers before releasing software.
Testing helps verify that the application works as expected and helps find bugs early, improving reliability.
What does the @SpringBootTest annotation do when placed on a test class?
Consider what kind of testing requires the full application setup.
@SpringBootTest loads the entire Spring application context, allowing integration tests that use all beans.
Given this Spring Boot test snippet, what error will occur if the MyService bean is missing?
@SpringBootTest
class MyServiceTest {
@Autowired
private MyService myService;
@Test
void testService() {
assertNotNull(myService);
}
}Think about what happens if Spring cannot find a required bean during context loading.
If a required bean is missing, Spring throws NoSuchBeanDefinitionException during context startup before tests run.
Which of the following is the correct way to write a test method in a Spring Boot test class using JUnit 5?
Remember JUnit 5 test methods can have default visibility and require an annotation.
JUnit 5 test methods must be annotated with @Test and can have package-private (default) visibility.
Consider this test class:
@SpringBootTest
class UserServiceTest {
@MockBean
private UserRepository userRepository;
@Autowired
private UserService userService;
@Test
void testFindUser() {
when(userRepository.findById(1L)).thenReturn(Optional.of(new User(1L, "Alice")));
User user = userService.findUser(1L);
assertEquals("Alice", user.getName());
}
}Why might this test fail with a NoSuchBeanDefinitionException for UserService?
Think about how Spring finds beans to inject.
If UserService is not annotated with @Service or @Component, Spring cannot create its bean, causing NoSuchBeanDefinitionException.