Bird
0
0

How do you correctly declare a mock bean for a Spring service named InventoryService using @MockBean?

easy📝 Syntax Q3 of 15
Spring Boot - Testing Spring Boot Applications
How do you correctly declare a mock bean for a Spring service named InventoryService using @MockBean?
A@Autowired private InventoryService inventoryService;
B@Mock private InventoryService inventoryService;
C@MockBean private InventoryService inventoryService;
D@MockBean private InventoryService inventoryService = new InventoryService();
Step-by-Step Solution
Solution:
  1. Step 1: Use @MockBean annotation

    @MockBean is used to create and inject a mock of the bean into the Spring context.
  2. Step 2: Declare the field without initialization

    The mock is created by Spring, so no manual instantiation is needed.
  3. Final Answer:

    @MockBean private InventoryService inventoryService; -> Option C
  4. Quick Check:

    Use @MockBean without manual instantiation [OK]
Quick Trick: Declare @MockBean field without new keyword [OK]
Common Mistakes:
  • Using @Mock instead of @MockBean in Spring Boot tests
  • Manually instantiating the mock bean which defeats @MockBean purpose

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes