0

我必须使用 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?

4

1 回答 1

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);
于 2016-07-29T11:16:09.650 回答