Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is the difference between @Mock, @MockBean, and @InjectMocks? @Mock, @MockBean और @InjectMocks में क्या अंतर है?

Answer

@Mock (Mockito) creates a mock object for use in plain unit tests that don't load any Spring context; it's paired with @ExtendWith(MockitoExtension.class). @InjectMocks creates an instance of the class under test and automatically injects the fields annotated with @Mock into it via constructor, setter, or field injection.

@MockBean is Spring Boot's test-specific annotation: it creates a Mockito mock and replaces the real bean of that type in the Spring application context, used inside @SpringBootTest or a slice test when you need the context to start but want to stub out one dependency (e.g. an external API client) rather than use the real implementation.

// Pure unit test
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
    @Mock private PaymentGateway paymentGateway;
    @InjectMocks private OrderService orderService;
}

// Spring context test with one dependency mocked
@WebMvcTest(OrderController.class)
class OrderControllerTest {
    @MockBean private OrderService orderService;
}

@Mock (Mockito) एक ऐसे प्लेन यूनिट टेस्ट में उपयोग के लिए मॉक ऑब्जेक्ट बनाता है जो कोई स्प्रिंग कॉन्टेक्स्ट लोड नहीं करता; इसे @ExtendWith(MockitoExtension.class) के साथ जोड़ा जाता है। @InjectMocks टेस्ट के तहत क्लास का एक इंस्टेंस बनाता है और @Mock से एनोटेट फील्ड्स को स्वचालित रूप से इसमें इंजेक्ट करता है।

@MockBean स्प्रिंग बूट का टेस्ट-विशिष्ट एनोटेशन है: यह एक Mockito मॉक बनाता है और स्प्रिंग एप्लिकेशन कॉन्टेक्स्ट में उस टाइप के वास्तविक बीन को बदल देता है, जिसका उपयोग @SpringBootTest या स्लाइस टेस्ट के अंदर होता है।

@WebMvcTest(OrderController.class)
class OrderControllerTest {
    @MockBean private OrderService orderService;
}

Was this answer clear?