In this article, we will show how to Mock classes with generic parameters using Mockito.
2. Test class
The FooService will be our simple test class with generic parameters:
The Car object will be used for parametrization of the FooService class:
Driver class is an object injected into the Car instance:
3. Using casting
To mock class with generic parameter we could use Mockito mock method with casting.
In this example, we used Mockito.mock(...) method to create a mock of FooService class. Then we cast it to the generic type FooService<Car>.
Note that there will be a warning:
but since it is just a JUnit class we could suppress this warning with the following annotation, and should not be worried about clean code that much:
4. Using @Mock annotation
The second way to mock a class with a generic parameter is to use @Mock annotation. This approach requires MockitoJUnitRunner:
In this example code we used @Mock annotation to create a mock object of FooService class. There is no obstacle to use a generic parameter for this object.
5. Conclusion
In this article, we present how to mock classes with generic parameters using Mockito.
As usual, code introduced in this article is available in our GitHub repository.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}