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

时间:2016-07-26 12:58:27

标签: java rest jersey jax-rs exceptionmapper

我必须使用jersey-test-framework-grizzly2测试Jersey 1.19。配置类包含已注册的REST端点和异常映射器类:

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?

1 个答案:

答案 0 :(得分:0)

将预期的班级类型更改为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);