Home > Java > javaTutorial > @Mock vs. @InjectMocks in Mockito: When to Use Which?

@Mock vs. @InjectMocks in Mockito: When to Use Which?

Mary-Kate Olsen
Release: 2024-11-24 06:49:16
Original
434 people have browsed it

@Mock vs. @InjectMocks in Mockito: When to Use Which?

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...
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template