Jersey状态测试 - ExceptionMapper - UniformInterfaceException当HTTP状态不是200

问题描述:

我必须使用jersey-test-framework-grizzly2测试Jersey 1.19。有配置类与注册的REST端点和异常映射类:Jersey状态测试 - ExceptionMapper - UniformInterfaceException当HTTP状态不是200

public class ConfiguredMyServiceTest extends JerseyTest { 

    @Override 
    protected int getPort(int defaultPort) { 
     return 8080; 
    } 

    public static class AppConfig extends DefaultResourceConfig { 
     public AppConfig() { 
      getSingletons().add(new ExceptionMapperProvider()); 
      getSingletons().add(new MyService()); 
     } 
    } 

    @Override 
    public WebAppDescriptor configure() { 
     return new WebAppDescriptor.Builder() 
      .initParam(WebComponent.RESOURCE_CONFIG_CLASS, 
       AppConfig.class.getName()) 
       .build(); 
    } 
} 

当我执行/测试返回HTTP状态200的REST端点它运作良好。

如果抛出异常,异常映射处理得很好,并返回形式对象javax.ws.rs.core.Response,错误代码:

@Provider 
@Singleton 
public class ExceptionMapperProvider implements ExceptionMapper<Exception>{ 

    @Override 
    public Response toResponse(final Exception exception){ 
     return Response.status(HttpStatusCodes.STATUS_CODE_SERVER_ERROR).entity(new BasicResponse(InternalStatus.UNHANDLED_EXCEPTION, exception.getMessage())).type(MediaType.APPLICATION_JSON).build(); 
    } 
} 

不过,我得到

com.sun.jersey.api.client.UniformInterfaceException: POST http://localhost:8080/v1/my-service/ returned a response status of 401 Unauthorized 

时我尝试在我的JUnit测试中声明Response。如何获得格式正确的响应,而不是UniformInterfaceException?

+0

你有任何身份验证处理程序,因为401意味着您无法进行身份验证?虽然我不知道你常量STATUS_CODE_SERVER_ERROR的计算结果。这实际上是一个401吗? –

+0

STATUS_CODE_SERVER_ERROR表示500.我简化了ExceptionMapper,所以有些部分被删除。但是,如果它的401,500或其他错误代码没有问题,问题是相同的 - 当我测试时,我得到UniformInterfaceException而不是Response。 – Justas

+2

我会建议启用日志过滤器,以便您可以看到请求/响应。如果您从未使用过,请点击此处。你看到请求打你的休息服务吗?以下是在客户端启用日志过滤器的示例。 http://*.com/questions/2332515/how-to-get-jersey-logs-at-server您也可能想要在LoggingFilter构造函数中将布尔printentity设置为true。这将验证401实际上来自服务器,而不是客户端配置的问题。 –

更改预期类类型com.sun.jersey.api.client.ClientResponse

protected ClientResponse executeGet(String path){ 
    WebResource resource = resource().path(path); 
    Builder builder = resource.header("Content-Type", "application/json;charset=UTF-8"); 
    return builder.get(ClientResponse.class); 
} 

现在它能够处理各种HTTP状态和分析基础响应:

ClientResponse clientResponse = executeGet("/info"); 

if (clientResponse.getStatus() == 200) 
    CustomResponseType customResponse = clientResponse.getEntity(CustomResponseType.class);