In this article, we will show how to Mock classes with generic parameters using Mockito.
2. Test class
FooService will be our simple test class with generic parameters:
Car object will be used for parametrization of the
Driver class is an object injected into the
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
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:
The second way to mock a class with a generic parameter is to use
@Mock annotation. This approach requires
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.
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.