我有REST web服务,我用Jersey test、Mockito、Junit进行了测试。当web服务方法成功执行时,我得到了正确的响应。在无效数据的情况下,将引发自定义异常,该异常必须由ExceptionMapper处理。它应该返回相同的结构响应,但使用不同的代码。ExceptionMapper在非测试环境中工作良好。但是,测试执行日志显示:
1 < 500
1 < Connection: close
1 < Content-Length: 1033
1 < Content-Type: text/html;charset=ISO-8859-1
1 < Date: Wed, 30 Mar 2016 11:55:37 GMT
javax.ws.rs.InternalServerErrorException: HTTP 500 Request failed.
at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:1020)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:816)
at org.glassfish.jersey.client.JerseyInvocation.access$700(JerseyInvocation.java:92)
我使用:
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>2.22.2</version>
</dependency>
通过测试类扩展的模拟服务的缩短版本:
public class MockedService extends JerseyTest {
@Override
public ResourceConfig configure() {
forceSet(TestProperties.CONTAINER_PORT, "8080");
enable(TestProperties.LOG_TRAFFIC);
return new ResourceConfig().register(new Service());
}
}
如何从ExceptionMapper获得响应?
您仍然需要注册ExceptionMapper
return new ResourceConfig()
.register(new Service())
.register(new YourMapper());
在您的真实环境中,可能会通过包扫描或类路径扫描来扫描映射器。