jeudi 26 mai 2016

"Request scope has already been shut down" jersey error in unit test

I'm writing a unit test which mocks out a resource using WireMock. I'm mocking my endpoint to throw an exception, e.g.:

    stubFor(
            post(urlEqualTo("/myEndpoint"))
            .willReturn(aResponse().withStatus(errorCode)
                    .withHeader("Content-Type", "application/json")
                    .withBody(errorJson)));

The relevant part of my client class which is under test here is:

import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;

public MyClient() {

    private Client client;
    private String baseUrl;

    ...

    public MyDto createObject(MyDto myDto) throws ClientErrorException {
        String resourcePath = MessageFormat.format("myEndpoint");

        return client.target(baseUrl)
                .path(resourcePath)
                .request(MediaType.APPLICATION_JSON_TYPE)
                .header(CONTENT_TYPE_HEADER, MediaType.APPLICATION_JSON)
                .post(Entity.entity(myDto, MediaType.APPLICATION_JSON), MyDto.class);
    }
}

In my unit test I'm trying to use junit's ExpectedException to catch and assert on the returned error, e.g.:

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void test_returnsError() {
    ...

    thrown.expect(NotAuthorizedException.class);
    thrown.expect(NotAuthorizedExceptionStatusMatcher.hasStatusAndError(401, UNAUTHORISED_ERROR));

    myClient.createObject(new MyDto());
}

Where NotAuthorizedExceptionStatusMatcher is my own customised matcher class:

import javax.ws.rs.NotAuthorizedException;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;

public class NotAuthorizedExceptionStatusMatcher extends TypeSafeMatcher<NotAuthorizedException> {

    public static NotAuthorizedExceptionStatusMatcher hasStatusAndError(int status, ErrorDescription entity) {
        return new NotAuthorizedExceptionStatusMatcher(status, entity);
    }

    private final int expectedStatus;
    private final ErrorDescription expectedError;

    private int actualStatus;
    private ErrorDescription actualError;

    private NotAuthorizedExceptionStatusMatcher(int expectedStatus, ErrorDescription expectedError) {
        this.expectedStatus = expectedStatus;
        this.expectedError = expectedError;
    }

    @Override
    public boolean matchesSafely(NotAuthorizedException exception) {
        actualStatus = exception.getResponse().getStatus();
        actualError = exception.getResponse().readEntity(ErrorDescription.class);
        return expectedStatus == actualStatus && expectedError.equals(actualError);
    }

    @Override
    public void describeTo(Description description) {
        description.appendValue(actualStatus)
                .appendText(" was found instead of ")
                .appendValue(expectedStatus)
                .appendText(" and ")
                .appendValue(actualError)
                .appendText(" was found instead of ")
                .appendValue(expectedError);
    }

}

When my matcher tries to do exception.getResponse().readEntity(ErrorDescription.class), I get an error:

java.lang.IllegalStateException: Request scope has been already shut down.
        at jersey.repackaged.com.google.common.base.Preconditions.checkState(Preconditions.java:149)
        at org.glassfish.jersey.process.internal.RequestScope.retrieveCurrent(RequestScope.java:239)
        at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:416)
        at org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:108)
        at com.lastmile.payments.payment.client.util.NotAuthorizedExceptionStatusMatcher.matchesSafely(NotAuthorizedExceptionStatusMatcher.java:28)
        at com.lastmile.payments.payment.client.util.NotAuthorizedExceptionStatusMatcher.matchesSafely(NotAuthorizedExceptionStatusMatcher.java:8)
        at org.hamcrest.TypeSafeMatcher.matches(TypeSafeMatcher.java:65)
        at org.hamcrest.core.AllOf.matches(AllOf.java:27)
        at org.hamcrest.DiagnosingMatcher.matches(DiagnosingMatcher.java:12)
        at org.junit.internal.matchers.StacktracePrintingMatcher.matchesSafely(StacktracePrintingMatcher.java:29)
        at org.junit.internal.matchers.StacktracePrintingMatcher.matchesSafely(StacktracePrintingMatcher.java:14)
        at org.hamcrest.TypeSafeMatcher.matches(TypeSafeMatcher.java:65)
        at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:12)
        at org.junit.Assert.assertThat(Assert.java:956)
        at org.junit.Assert.assertThat(Assert.java:923)
        at org.junit.rules.ExpectedException.handleException(ExpectedException.java:252)
        at org.junit.rules.ExpectedException.access$000(ExpectedException.java:106)
        at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:241)
        at com.github.tomakehurst.wiremock.junit.WireMockRule$1.evaluate(WireMockRule.java:67)
        at org.junit.rules.RunRules.evaluate(RunRules.java:20)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:242)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:137)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
        at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
        at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)

This same code seems to work if I use a try-catch block to assert on the exception, but I prefer the ExpectedException approach. Any ideas what might be the cause here? I suspect it's a combination of the frameworks I'm using but I'm not quite sure where to go from here.

Aucun commentaire:

Enregistrer un commentaire