【问题标题】:How do I get the status code & response headers of a jersey/dropwizard response, when testing?在测试时,如何获取球衣/dropwizard 响应的状态代码和响应标头?
【发布时间】:2017-05-09 21:49:01
【问题描述】:

我正在为我的 dropwizard 资源进行单元测试(由模拟支持)。我最近添加了一些响应头和不同的状态代码,并想测试它们。

不幸的是,我在他们的文档中找不到一个示例,他们可以同时获取实体并检查响应。

我正在测试的方法返回一个文件。方法本身定义为:

@GET
@Path("/{assetId}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@PermitAll
public Response download(@Auth User user,
                         @PathParam("assetId") String assetId,
                         @HeaderParam("Range") String rangeHeader) {

为了验证下载,我最初从我的测试中发出这样的请求:

    final InputStream responseStream = resource.client()
        .target("/assets/123")
        .request()
        .get(InputStream.class);

然后我可以将流写入文件并验证它是从资源返回的文件。工作得很好。 (这里,“资源”是 dropwizard 的 ResourceTestRule。)

但是,如上所述,我现在想要处理响应本身。有一些使用 Jersey 的 ClientResponse 的示例,但(还)不起作用。我试过了:

    final ClientResponse response = resource.client()
        .target("/assets/123")
        .request()
        .get(ClientResponse.class);

但是,这最终会出现异常:

javax.ws.rs.client.ResponseProcessingException: org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=application/octet-stream, type=class org.glassfish.jersey.client.ClientResponse, genericType=class org.glassfish.jersey.client.ClientResponse.

at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:811)
at org.glassfish.jersey.client.JerseyInvocation.access$700(JerseyInvocation.java:92)
at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:701)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)

...我不知道该怎么办。有什么帮助吗?

谢谢

【问题讨论】:

    标签: java unit-testing jersey dropwizard


    【解决方案1】:

    啊,这比我想象的要简单。

        final Response response = resource.client()
            .target("/assets/123")
            .request()
            .get();
    
        InputStream responseStream = (InputStream) response.getEntity();
    

    【讨论】:

    • 如果可以解决问题,您应该接受自己的答案。这样一来,其他读者就会收到关于所描述问题的解决方案的视觉通知。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 2015-06-08
    • 2011-10-07
    • 1970-01-01
    • 2018-03-27
    相关资源
    最近更新 更多