Bird
0
0

Consider this test code snippet:

medium📝 Debug Q14 of 15
Spring Boot - Testing Spring Boot Applications
Consider this test code snippet:
@MockBean
private OrderService orderService;

@Test
void testOrder() {
  orderService.placeOrder();
  verify(orderService).placeOrder();
}

When running this test, it fails with a NullPointerException. What is the most likely cause?
AThe <code>orderService</code> is not mocked properly because it is private
BThe <code>verify</code> method is called before <code>placeOrder()</code>
CThe <code>placeOrder()</code> method is final and cannot be mocked
DThe <code>@MockBean</code> annotation was not processed because the test class lacks <code>@SpringBootTest</code>
Step-by-Step Solution
Solution:
  1. Step 1: Check test setup requirements

    @MockBean requires Spring Boot test context to process annotations, usually via @SpringBootTest or similar.
  2. Step 2: Identify cause of NullPointerException

    If @MockBean is not processed, orderService remains null, causing NPE when calling placeOrder().
  3. Final Answer:

    The @MockBean annotation was not processed because the test class lacks @SpringBootTest -> Option D
  4. Quick Check:

    @MockBean needs Spring context [OK]
Quick Trick: Always use @SpringBootTest to enable @MockBean processing [OK]
Common Mistakes:
  • Assuming private fields can't be mocked
  • Misordering verify and method calls
  • Not realizing final methods can't be mocked (but not cause NPE here)

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes