I have the following method for which I'm trying to write unit test using Mockito. I'm fairly new to Mockito and trying to catch up.
Method to test
public synchronized String executeReadRequest(String url) throws Exception{
String result = null;
RestClient client = null;
Resource res = null;
logger.debug("Start executing GET request on "+url);
try{
client = getClient();
res = client.resource(url);
result = res.contentType(this.requestType).accept(this.responseType).get(String.class);
}
catch(Exception ioe){
throw new Exception(ioe.getMessage());
}
finally{
res = null;
client = null;
}
logger.info("GET request execution is over with result : "+result);
return result;
}
The unit test with Mockito
@Test
public void testRestHandler() throws Exception {
RestHandler handler = spy(new RestHandler());
RestClient mockClient = Mockito.mock(RestClient.class,Mockito.RETURNS_DEEP_STUBS);
Resource mockResource = Mockito.mock(Resource.class,Mockito.RETURNS_DEEP_STUBS);
doReturn(mockClient).when(handler).getClient();
Mockito.when(mockClient.resource(Mockito.anyString())).thenReturn(mockResource);
//ClassCastException at the below line
Mockito.when(mockResource.contentType(Mockito.anyString()).accept(Mockito.anyString()).get(Mockito.eq(String.class))).thenReturn("dummy read result");
handler.setRequestType(MediaType.APPLICATION_FORM_URLENCODED);
handler.setResponseType(MediaType.APPLICATION_JSON);
handler.executeReadRequest("abc");
}
But I'm getting a ClassCastException at the line
Mockito.when(mockResource.contentType(Mockito.anyString()).accept(Mockito.anyString()).get(Mockito.eq(String.class))).thenReturn("dummy read result");
Exception
java.lang.ClassCastException: org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$4b441c4d cannot be cast to java.lang.String
Appreciate any help to resolve this.
Many thanks.