如何在JAR中模拟服务

时间:2014-07-05 12:42:26

标签: java junit mockito

我有一个班级

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();
}
}

我的测试用例如下

 @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类在我的JAR文件中可能是这个测试失败的原因??? 我应该测试验证JAR中的方法,即Service2 Class ??? 我可以用这个 verify(mockService).method2("1"); //我正在使用此功能,但收到的错误是说需要但未调用

1 个答案:

答案 0 :(得分:1)

问题是,您尝试在JSONObject语句中匹配的when与将传递给您的方法的verify不一致(对象标识),而您是在readJsonString()声明中使用。这是因为JSONOBject每次都会返回一个新对象。

初始化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)); 一次,并将其重新用于Mockito.eq() matcher中包含的两个语句。

{{1}}