Mockito is one of the most popular testing frameworks that allows creating mocked and spied objects to verify the behavior of the tested class. In this article, we are going to present @InjectMocks annotations that are used to inject all mocked objects into the testing class.
2. Using @InjectMocks for dependency injection
The @InjectMocks annotation is used to insert all dependencies into the test class. Mockito can inject mocks using constructor injection, setter injection, or property injection.
Let's check a simple example:
We have a simple POJO class that holds Post data with the following structure:
The DBConnection class is responsible for opening and closing database connection:
Finally, PostResource will be our main class for testing:
In the following example, we used @InjectMocks to inject the DBConnection mocked object into the PostResource object.
PostResource object call methods from mocked DBConnection class. Mockito is used here to verify if open() and close() method were called when calling getPosts() method on PostResource object. @InjectMocks annotation creates an instance of a real object, thats why we get 3 posts in the test.
4. Conclusion
In this article, we covered @InjectMocks annotation functionality. Mockito allows injecting mocks by constructor, property, or setter method. Note that to make this annotation work you need to enable it by adding @RunWith(MockitoJUnitRunner.class) at the top of the unit test class, call MockitoAnnotations.initMocks(this) method in the @Before JUnit method.
As usual code used in this article is available under GitHub
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}