Mock method using generic types

Given this interface :

public interface JsonService {
    <T> T read(String path, Class<T> valueType);
}

The method is used this way :

MyClass object = jsonService.read("file.json", MyClass.class);

I want to write unit tests, and to mock this method. With Mockito, I have mocked the jsonService :

private final JsonService jsonService = Mockito.mock(JsonService.class);

I mocked the method the best I could :

when(jsonService.<MyClass>read(any(String.class), any(Class.class))).thenReturn(nonNullObject);

When the test runs, the method .read() returns null instead of my “nonNullObject” object. I think this has to do with the any(Class.class) that doesn’t match with MyClass.class.

Thank you for your help

Answer

you can have strict matchers

when(jsonService.<MyClass>read(eq("file.json"), 
       eq(MyClass.class))).thenReturn(nonNullObject);

Leave a Reply

Your email address will not be published. Required fields are marked *