Testing expected exception with JerseyTest - Test container returns 500

357 views Asked by At

I am using:

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

For REST testing of my resources. While everything works well on the positive side, when my resource throws a custom exception it is always discarded, and a 500 exception is returned by the test container.

For example:

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

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

When I want to test it:

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

Actual response returned:

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

How can I fix this in order to test the logic throwing expected exceptions by my resources?

1

There are 1 answers

1
Nom1fan On

After further investigation I realized my custom exception is mapped by an exception mapper:

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

I simply needed to register this mapper on ResourceConfig:

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

And now it works as expected.