Bird
0
0

You want to test a controller OrderController that depends on a service OrderService. Using @WebMvcTest, how can you provide a mock OrderService to the controller during testing?

hard📝 Application Q15 of 15
Spring Boot - Testing Spring Boot Applications
You want to test a controller OrderController that depends on a service OrderService. Using @WebMvcTest, how can you provide a mock OrderService to the controller during testing?
ACreate a new OrderService instance manually in the test method
BUse @Autowired on OrderService field to inject real service
CUse @MockBean on OrderService field in the test class to inject a mock
DUse @SpringBootTest instead of @WebMvcTest to load full context
Step-by-Step Solution
Solution:
  1. Step 1: Understand @WebMvcTest scope

    @WebMvcTest loads only web layer, so service beans are not loaded automatically.
  2. Step 2: Use @MockBean to provide mock dependencies

    Annotating OrderService with @MockBean in the test class creates and injects a mock into the controller.
  3. Final Answer:

    Use @MockBean on OrderService field in the test class to inject a mock -> Option C
  4. Quick Check:

    @MockBean mocks service dependencies in @WebMvcTest [OK]
Quick Trick: Use @MockBean to mock services in @WebMvcTest [OK]
Common Mistakes:
  • Trying to @Autowired real service in @WebMvcTest
  • Not mocking service causing NoSuchBeanDefinitionException
  • Switching to @SpringBootTest unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes