Bird
0
0

Consider this test class:

medium📝 Debug Q6 of 15
Spring Boot - Testing Spring Boot Applications
Consider this test class:
@WebMvcTest(controllers = ProductController.class)
class ProductControllerTest {
  @Autowired
  private MockMvc mockMvc;

  @MockBean
  private ProductService productService;

  @Test
  void testGetProduct() throws Exception {
    when(productService.getProduct(1L)).thenReturn(new Product(1L, "Book"));
    mockMvc.perform(get("/products/1"))
      .andExpect(status().isOk())
      .andExpect(jsonPath("$.name").value("Book"));
  }
}
What is the purpose of the @MockBean annotation here?
ATo create a mock of ProductService and inject it into the controller
BTo load the real ProductService bean from the context
CTo disable ProductService during the test
DTo create a spy of ProductService that calls real methods
Step-by-Step Solution
Solution:
  1. Step 1: Understand @MockBean role

    @MockBean creates a mock instance of the bean and injects it into the Spring context for the test.
  2. Step 2: Analyze usage in controller test

    This mock replaces the real ProductService so the controller uses the mocked behavior defined in the test.
  3. Final Answer:

    To create a mock of ProductService and inject it into the controller -> Option A
  4. Quick Check:

    @MockBean mocks and injects dependencies [OK]
Quick Trick: @MockBean mocks and injects dependencies for controller tests [OK]
Common Mistakes:
  • Thinking @MockBean loads real beans
  • Assuming it disables the bean
  • Confusing mock with spy

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes