When to Use @Mock vs. @InjectMocks in Mockito
Mockito is a popular framework for mocking and unit testing in Java. It provides two annotations for mocking: @Mock and @InjectMocks. It's crucial to understand their distinctions to effectively utilize mocks in your tests.
@Mock
@Mock is employed to generate a mock object. When you annotate a field with @Mock, Mockito creates an object of the specified class and registers it as a mock. This mock will adhere to the mock's interface's behavior, providing a substitute for real objects in your tests.
@InjectMocks
In contrast, @InjectMocks annotates an instance of a class under test. Mockito injects mock objects that were created with @Mock annotations into this instance. This technique allows you to test the behavior of the class under test while interacting with specific mock dependencies.
Usage Considerations
To utilize @Mock and @InjectMocks, you'll need to initialize the mocks and inject them. In JUnit 4, use @RunWith(MockitoJUnitRunner.class) or Mockito.initMocks(this). For JUnit 5, employ @ExtendWith(MockitoExtension.class).
Example
Consider the following example illustrating the usage of @Mock and @InjectMocks:
// JUnit 4 @RunWith(MockitoJUnitRunner.class) public class SomeManagerTest { @InjectMocks private SomeManager someManager; @Mock private SomeDependency someDependency; // injected into someManager // tests... }
In this example, someManager is injected with the mock instance someDependency. Tests can now assert how someManager interacts with this mock.
Conclusion
Using @Mock and @InjectMocks appropriately is essential for effective Mockito-based unit testing. By clearly understanding their roles, you can ensure the accuracy and reliability of your tests.
The above is the detailed content of @Mock vs. @InjectMocks in Mockito: When to Use Which?. For more information, please follow other related articles on the PHP Chinese website!