Reputation: 181
I have one class
class ServiceA{
public Service2 service2Obj;
public ServiceA(){
}
public ServiceA(Service2 service2Obj){
this.service2Obj = service2Obj;
}
public Response updateMetadata(String templateId,
InputStream metadataStream)
throws InternalServerError,ServiceException,
NotFoundException {
ObjectMapper mapper = new ObjectMapper();
Map<String, String> metadataMap = null;
String status = null;
metadataMap = mapper.readValue(metadataStream, Map.class);
String i = service2Obj.updateMetadataService(templateId, metadataMap);
}
return Response.ok().entity(i).build();
}
}
My test case is as follows
@Test
public void test(){
Service2 mockService = Mockito.mock(Service2.class);
ServiceA ServiceAObj= new ServiceA(mockService);
Mockito.when(mockService.updateMetadataService("1", readJsonString()))
.thenReturn(readJsonString());
// run method under test
Response response = ServiceAObj.updateMetadata("1",new ByteArrayInputStream(
"{\"title\":\"TEST\"}".getBytes());
Assert.assertEquals(200, response.getStatus());
// Parse json and get value from json string
String totalItems = (String) convertMapToJson(
(response.readEntity(Object.class))).get("title");
Mockito.verify(mockDocStoreImpl).updateMetadataService("1",readJsonString()); // getting here error wanted but not invoked
}
public static JSONObject readJsonString(String json)
throws DocGenServiceException {
String json = "{\"title\":\"TEST\"}";
JSONObject obj = new JSONObject(json);
return obj;
}
Service2 class is in my JAR file could this be the reason of failure of Test ???
Should I test to verify the method in JAR, i.e. Service2 Class???
Can I use this
verify(mockService).method2("1");
// i am using this but getting error saying wanted but not invoked
Upvotes: 1
Views: 1767
Reputation: 97120
The issue is that the JSONObject
that you try to match on in your when
statement is not the same (object identity) as the one that will be passed to your method, and the one you use in your verify
statement. This is due to the fact that readJsonString()
will return a new object every time.
Initialize your JSONOBject
once and reuse it for both statements wrapped in a Mockito.eq()
matcher.
JSONObject json = readJsonString();
Mockito.when(mockService.updateMetadataService(
Mockito.eq("1"), Mockito.eq(json))).thenReturn(json);
// ...
Mockito.verify(mockDocStoreImpl).updateMetadataService(
Mockito.eq("1"), Mockito.eq(json));
Upvotes: 1