junitjerseymockitojersey-test-frameworkexceptionmapper

Jersey test - ExceptionMapper is not invoked


I have REST web service which I test with Jersey Test, Mockito, Junit. When web service method is executed successfully, I get correct response. In case of invalid data, custom exception is thrown which must be handled by ExceptionMapper. It should return the same structure response but with different codes. ExceptionMapper works well in not test environment. However, after test execution logs show:

1 < 500
1 < Connection: close
1 < Content-Length: 1033
1 < Content-Type: text/html;charset=ISO-8859-1
1 < Date: Wed, 30 Mar 2016 11:55:37 GMT

javax.ws.rs.InternalServerErrorException: HTTP 500 Request failed.
at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:1020)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:816)
at org.glassfish.jersey.client.JerseyInvocation.access$700(JerseyInvocation.java:92)

I use:

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

Shortened version of mocked service which is extented by test classes:

public class MockedService extends JerseyTest {

    @Override
    public ResourceConfig configure() {

        forceSet(TestProperties.CONTAINER_PORT, "8080");
        enable(TestProperties.LOG_TRAFFIC);

        return new ResourceConfig().register(new Service());
    }
}

How to get response from ExceptionMapper?


Solution

  • You still need to register the ExceptionMapper

    return new ResourceConfig()
            .register(new Service())
            .register(new YourMapper());
    

    In your real environment, the mapper is probably scanned for, either with package scanning or classpath scanning.