你不能这样测试。你在这里做什么
Response response = Response.status(Response.Status.OK)
.entity(entity)
.type(MediaType.APPLICATION_JSON).build();
正在建设一个outbound回复。在 JAX-RS 框架中,在我们发出响应后,例如
@GET
@Produced(MediaType.APPLICATION_JSON)
public Response getResponse() {
...
return Response.status(Response.Status.OK)
.entity(entity)
.type(MediaType.APPLICATION_JSON).build();
}
它仍然需要通过一个MessageBodyWriter用于序列化为 JSON。
话虽这么说,泽西岛有一个测试框架,我们可以用来测试我们的资源方法。你可以找到所有官方示例在Github上
示例(有一些改动):
这些是 Maven 所需的最低依赖项
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.test-framework</groupId>
<artifactId>jersey-test-framework-core</artifactId>
<version>2.13</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>2.13</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.13</version>
</dependency>
</dependencies>
测试班
public class TestJSONResource extends JerseyTest {
@Override
protected TestContainerFactory getTestContainerFactory() {
return new GrizzlyTestContainerFactory();
}
@Path("test")
public static class TestResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getJson() {
Map<String, String> entity = Maps.newHashMap();
entity.put("foo", "bar");
Response response = Response.status(Response.Status.OK)
.entity(entity)
.type(MediaType.APPLICATION_JSON).build();
return response;
}
}
@Override
protected DeploymentContext configureDeployment() {
return DeploymentContext.builder(new ResourceConfig(TestResource.class))
.contextPath("context1/context2")
.build();
}
@Test
public void testGet() {
final WebTarget target = target("test");
final String s = target.request().get(String.class);
System.out.println(s);
}
}
jersey-media-json-jackson
提供了MessageBodyWriter
and MessageBodyReader
用于处理 JSON,它是为我们隐式注册的。