Q1. How do you write unit tests for Spring components?
Use JUnit 5 with Mockito. For service layer tests, you can mock dependencies using @Mock and @InjectMocks. Use @ExtendWith(MockitoExtension.class). Example:
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock UserRepository repository;
@InjectMocks UserService service;
@Test
void testFindUser() {
when(repository.findById(1L)).thenReturn(Optional.of(new User()));
assertNotNull(service.getUser(1L));
}
}
Q2. What is Mockito?
Mockito is a mocking framework for unit tests. It allows you to create mock objects, define their behavior, and verify interactions. It's commonly used with JUnit to test Spring components in isolation.
Q3. What is @InjectMocks?
@InjectMocks is a Mockito annotation that creates an instance of the class and injects the mocks (annotated with @Mock) into it. This is used for the class under test.
Q4. How do you test controllers in Spring?
Use @WebMvcTest to load only web layer, and @MockBean for dependencies. Then use MockMvc to perform requests and assert responses. Example:
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired MockMvc mockMvc;
@MockBean UserService service;
@Test
void testGetUser() throws Exception {
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk());
}
}
Q5. What is the difference between @Mock and @MockBean?
@Mock is a Mockito annotation used in plain unit tests. @MockBean is a Spring Boot annotation used in tests to add mocks to the Spring application context, replacing any existing bean of the same type. @MockBean is used in integration tests like @SpringBootTest or @WebMvcTest.
