json - 使用mockito调用Rest方法

标签 json junit jersey httprequest mockito

我使用 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/

相关文章:

java - Android Maven 插件执行测试时运行时异常

java - 无法使用 Tomcat 6 部署 JAX-RS (Jersey 2.3.1) Web 服务

c# - 使用 System.Web.Script.Serialization.JavascriptSerializer 反序列化 JSON - 怎么做?

javascript - .net 中的日期与 javascript 中的日期

javascript - 哪个 HTML 元素可以保存一串 javascript 代码而不需要浏览器对其进行评估?

java - ClassLoader.getSystemClassLoader().getResource() 在 servlet 容器和测试环境中的不同行为

java - Spring4 JUnit 测试 : Load SQL to a H2 db

javascript - 在 Javascript + MVC3 中使用 Json 解析实体列表

java - 在方法中传递 2 个 json 格式的对象

java - 使用 JerseyIncation 构建器测试放置格式错误的 json