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

Jersey test - ExceptionMapper - UniformInterfaceException when HTTP status is not 200

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

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();
    }
}

当我 execute/test REST 端点 returns HTTP 状态 200 时,它运行良好。

如果抛出异常,异常映射器会很好地处理它并形成 return 对象 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?

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