我使用 Jersey,并且有以下 Rest 函数,该函数在部署我的服务器时返回 JSON 字符串:
@GET
@Path("getallemployees")
@Produces("application/json")
public Response getAllEmployees() {
//building the entity object which is List<Employee>
return Response.ok(entity).build();
}
我需要开发一些单元测试(不是集成测试),并且我想以某种方式模拟调用此方法的 HTTPRequest,然后获取 json 字符串。最好的选择是使用mockito。
有什么建议吗?
谢谢!!
最佳答案
问题在于该方法向调用者返回一个位于框架代码深处的Response
对象。它不返回 JSON 字符串。
如果您需要模拟方法本身内部的某些内容,您可以使用 Mockito。这应该可行。
但是,如果您将 Jackson 与 Jersey 一起使用,您可能需要获取该方法返回的值并将其转换为 JSON,如下所示。
Response response = getAllEmployees();
Object retval = response.getEntity();
try {
ObjectMapper mapper = new ObjectMapper();
// I like this formatting. You can change it.
mapper.configure(Feature.INDENT_OUTPUT, true);
mapper.configure(Feature.WRITE_ENUMS_USING_TO_STRING, true);
mapper.configure(Feature.USE_ANNOTATIONS, false);
mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
mapper.setSerializationInclusion(Inclusion.NON_NULL);
mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
mapper.getSerializationConfig().withSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
String json = mapper.writeValueAsString(retval);
... assert something about the string
} catch (JsonProcessingException e) {
// do something
} catch (IOException e) {
// do something
}
关于json - 使用mockito调用Rest方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17620934/