【问题标题】:Testing expected exception with JerseyTest - Test container returns 500使用 JerseyTest 测试预期异常 - 测试容器返回 500
【发布时间】:2022-01-03 07:58:24
【问题描述】:

我正在使用:

<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>2.27</version>

用于我的资源的 REST 测试。虽然从积极的方面来说一切正常,但当我的资源抛出自定义异常时,它总是会被丢弃,并且测试容器会返回 500 异常。

例如:

//Omitting all annotations for brevity
import org.rest.exception.NotFoundException;

public class MyResource {
  
   
   public void myAPI() {
     throw new NotFoundException("Alarm! Not Found!");
   }
}

当我想测试它时:

import javax.ws.rs.core.Response;

public class MyJerseyTest extends JerseyTest {
   
   public void myTest() {
      Response response = target("path...").request().get();
      assertEquals(response.getStatus(), HttpStatus.SC_NOT_FOUND);
   }
}

返回的实际响应:

InboundJaxrsResponse{context=ClientResponse{method=GET, uri=http://localhost:9998/path, status=500, reason=Request failed.}}

如何解决这个问题,以便测试我的资源引发预期异常的逻辑?

【问题讨论】:

  • 您是否尝试过在 throw 异常语句上使用断点进行调试?看起来您的 Jersey 配置或“路径...”的映射没有考虑您的代码。
  • 请看我贴的答案。

标签: java jersey-test-framework


【解决方案1】:

经过进一步调查,我意识到我的自定义异常是由异常映射器映射的:

@Component
@Provider
public class NotFoundExceptionMapper implements ExceptionMapper<NotFoundException> {

    @Override
    public Response toResponse(NotFoundException exception) {
        ErrorResponse errorResponse = new ErrorResponse(Response.Status.NOT_FOUND.getStatusCode(),
                exception.getMessage());
        return Response.status(Response.Status.NOT_FOUND).type(MediaType.APPLICATION_JSON).entity(errorResponse)
                .build();
    }
}

我只需要在ResourceConfig注册这个映射器:

@Override
protected Application configure() {
ResourceConfig application = new ResourceConfig();
application.register(NotFoundExceptionMapper.class);
return application;

现在它按预期工作了。

【讨论】:

  • 是的,我就是这个意思。您的配置需要了解自定义映射。恭喜。
猜你喜欢
  • 2015-08-09
  • 2011-07-31
  • 2019-01-23
  • 2016-03-20
  • 2012-04-05
  • 2013-10-08
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
相关资源
最近更新 更多