4

我有 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 获得响应?

4

1 回答 1

9

您仍然需要注册ExceptionMapper

return new ResourceConfig()
        .register(new Service())
        .register(new YourMapper());

在您的真实环境中,可能会使用包扫描或类路径扫描来扫描映射器。

于 2016-03-30T12:12:42.543 回答