Problems running JerseyTest when dealing with HttpServletResponse
Asked Answered
A

7

22

Here is a sample Resource class:

@Path("/resource") 
public class SomeResource { 
    @GET 
    @Produces({MediaType.APPLICATION_XML}) 
    public String someMethod(@QueryParam("param1") String param1, ..., @Context HttpServletRequest request) { 
            String remoteUser = request.getRemoteAddr(); 
            // Business logic here. 
            return response; 
    } 
} 

And the JerseyTest for the resource:

public class TestSomeResource extends JerseyTest    { 
    @Override 
    protected Application configure() { 
            enable(TestProperties.LOG_TRAFFIC); 
            return new ResourceConfig(SomeResource.class); 
    } 

    @Test 
    public void testXMLResponse()   { 
            String response = target("resource") 
                            .queryParam("param1", param1) 
                            // More parameters here. 
                            .request() 
                            .accept(MediaType.APPLICATION_XML) 
                            .get(String.class); 
            // Some assertions on response. 
    } 
} 

I am able to run jersey tests for all other resources except the ones using @Context HttpServletRequest as an input parameter. It gives a InternalServerErrorException: HTTP 500 Internal Server Error.

Following is the stacktrace:

javax.ws.rs.InternalServerErrorException: HTTP 500 Internal Server Error 
    at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:904) 
    at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:749) 
    at org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocation.java:88) 
    at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:650) 
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315) 
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297) 
    at org.glassfish.jersey.internal.Errors.process(Errors.java:228) 
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:421) 
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:646) 
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:375) 
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:275) 
    at com.mysample.TestSomeResource.testXMLResponse(TestSomeResource.java:15) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 
    at java.lang.reflect.Method.invoke(Method.java:597) 
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) 
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) 
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) 
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) 
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) 
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27) 
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) 
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) 
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) 
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) 
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) 
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) 
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) 
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) 
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309) 
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) 
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) 
Addams answered 31/7, 2013 at 14:32 Comment(2)
Which is line 15 of TestSomeResource.java?Baroness
It is the .get(String.class) inside testXMLResponse(). In general, I would be also happy if you could point me out documentation related to JerseyTest when dealing with @Context HttpServletRequest. Thanks!Addams
E
24

You exception is related to the fact that the HttpServletRequest is null.

Jersey documentation says:

3.6. Use of @Context

Previous sections have introduced the use of @Context. Chapter 5 of the JAX-RS specification presents all the standard JAX-RS Java types that may be used with @Context.

When deploying a JAX-RS application using servlet then ServletConfig, ServletContext, HttpServletRequest and HttpServletResponse are available using @Context.

I'm guessing that you use jersey-test-framework-provider-grizzly2 which doesn't support it.

If you want to have access to HttpServletResponse remove that dependency and add:

<dependency>
    <groupId>org.glassfish.jersey.test-framework</groupId>
    <artifactId>jersey-test-framework-core</artifactId>
    <version>2.1</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-grizzly2-servlet</artifactId>
    <version>2.1</version>
</dependency>

Now you actually want to tell JerseyTest to start the right test server, to do that you have to override a method protected TestContainerFactory getTestContainerFactory(). Please be sure to replace <your-java-package> with the actual name of your package.

@Override
protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
    return new TestContainerFactory() {
        @Override
        public TestContainer create(final URI baseUri, final ApplicationHandler application) throws IllegalArgumentException {
            return new TestContainer() {
                private HttpServer server;

                @Override
                public ClientConfig getClientConfig() {
                    return null;
                }

                @Override
                public URI getBaseUri() {
                    return baseUri;
                }

                @Override
                public void start() {
                    try {
                        this.server = GrizzlyWebContainerFactory.create(
                                baseUri, Collections.singletonMap("jersey.config.server.provider.packages", "<your-java-package>")
                        );
                    } catch (ProcessingException e) {
                        throw new TestContainerException(e);
                    } catch (IOException e) {
                        throw new TestContainerException(e);
                    }
                }

                @Override
                public void stop() {
                    this.server.stop();
                }
            };

        }
    };
}

You can also check org.glassfish.jersey.test.grizzly.GrizzlyTestContainerFactory for better implementation of the factory.

Emilemile answered 1/8, 2013 at 8:47 Comment(7)
I had used grizzly2 container which JerseyTest supports.Addams
Check my updated answer, this way you can still use Grizzly and it should work now.Emilemile
Thanks..!!! Your solution worked for me. I had even posted to jersey forums but no one replied. Unfortunately I was not using maven so had to play around with a couple of jars.Addams
Not enough reputation to +1 but accepted the answer. Any reference to good tutorials or documentation will also be helpful.Addams
I would say that official documentation on jersey.java.net/documentation/latest/user-guide.html is quite okay.Emilemile
Thanks, this addressed the problem for me. I guess the only thing I don't understand is why jersey-test-framework-provider-grizzly2 doesn't just do this.Dinar
Do you know how to configure the Grizzly container using the JAX-RS application object?Blip
C
13

You can also inject a mocked HttpServletRequest object in the configure method. Here is an Jersey 1 example:

public abstract class AbstractIntegrationTest extends AbstractJerseyTest {

    protected HttpServletRequest httpServletRequest;

    @Override
    protected void configure(final ResourceConfig config) throws Exception {
        // create a mock and inject it via singleton provider
        httpServletRequest = mock(HttpServletRequest.class);
        config.getSingletons().add(
                new SingletonTypeInjectableProvider<Context, HttpServletRequest>(
                        HttpServletRequest.class, httpServletRequest) {});
    }

}

Jersey 2:

final HttpServletRequest request = mock(HttpServletRequest.class);
resourceConfig.register(new AbstractBinder() {
                            @Override
                            protected void configure() {
                                bind(request).to(HttpServletRequest.class);
                            }
                        });
Cholula answered 28/10, 2014 at 13:14 Comment(2)
Had this problem with Jersey 2. This allows for a less-verbose test class. Thanks!Kaylakayle
This seems the best option as we don't need to do a lot of changesSubstructure
A
1

So finally I get working solution (It close to most popular answer but with small changes):


pom.xml

<properties>    
  <jersey.version>2.22.1</jersey.version>
</properties>

    <dependency>
        <groupId>org.glassfish.jersey.test-framework.providers</groupId>
        <artifactId>jersey-test-framework-provider-inmemory</artifactId>
        <version>${jersey.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-grizzly2-servlet</artifactId>
        <version>${jersey.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>

Add following abstract class to application:

import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.grizzly2.servlet.GrizzlyWebContainerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.test.DeploymentContext;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
import org.glassfish.jersey.test.spi.TestContainer;
import org.glassfish.jersey.test.spi.TestContainerException;
import org.glassfish.jersey.test.spi.TestContainerFactory;

import javax.ws.rs.ProcessingException;
import javax.ws.rs.core.Application;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;

public abstract class RestTest extends JerseyTest {

    @Override
    protected Application configure() {
        enable(TestProperties.LOG_TRAFFIC);
        return new ResourceConfig();
    }

    abstract protected String getRestClassName();

    @Override
    protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
        return new TestContainerFactory() {
            @Override
            public TestContainer create(URI baseUri, DeploymentContext deploymentContext) {
                return new TestContainer() {
                    private HttpServer server;

                    @Override
                    public ClientConfig getClientConfig() {
                        return null;
                    }

                    @Override
                    public URI getBaseUri() {
                        return baseUri;
                    }

                    @Override
                    public void start() {
                        try {
                            this.server = GrizzlyWebContainerFactory.create(
                                    baseUri, Collections.singletonMap(ServerProperties.PROVIDER_CLASSNAMES, getRestClassName())
                            );
                        } catch (ProcessingException | IOException e) {
                            throw new TestContainerException(e);
                        }
                    }

                    @Override
                    public void stop() {
                        this.server.shutdownNow();

                    }
                };
            }
        };
    }

}

And to test Rest you need do like this:

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;

import static org.junit.Assert.assertEquals;

public class YourRestTest extends RestTest {

    private static final Logger LOG = LoggerFactory.getLogger("TestLog");

    @Override
    protected String getRestClassName() {
        return "com.app.rest.YourRest";
    }


    @Test
    public void test() throws URISyntaxException, IOException {
        String ttt = new String(Files.readAllBytes(Paths.get(YourRestTest.class.getResource("/rest_resource/ttt.json").toURI())));
        Response response = target("/xxx").path("/yyyy").request().post(Entity.entity(ttt, "application/json"));
        assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    }
}
Adaptive answered 17/12, 2015 at 8:55 Comment(0)
A
0

Also see peeskillet's answers on this stackoverflow thread: [link]

(none of the currently listed solutions worked for me)

Aida answered 21/7, 2016 at 17:20 Comment(0)
S
0

Seems like this problem has been there since a long time ago. As @lpiepiora's explaination, we need a Servlet-based test container. And there already is one in jersey-test-framework-provider-grizzly2 (don't know if there is it when the question posted), which is GrizzlyWebTestContainerFactory, and it requires a different DeploymentContext. Pull the newest git and you'll find an example in test-framework/providers/grizzly2/src/test/java/org/glassfish/jersey/test/grizzly/web/GrizzlyWebTest.java. To be straight and simple, you just need to add these overrides in your base test class:

// --- For Servlet-based test container --- begins ---

@Override
protected DeploymentContext configureDeployment() {
    return ServletDeploymentContext.forServlet(new ServletContainer(new YourResourceConfig())).build();
}

@Override
protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
    return new GrizzlyWebTestContainerFactory();
}

// --- For Servlet-based test container --- ends ---

// other stuff...

(Replace YourResourceConfig with your real one.)

EDIT: If you use Jersey with jersey-spring3, you will find the solution above fails because of the absence of all your Spring beans. To fix it:

@Override
protected DeploymentContext configureDeployment() {
    return ServletDeploymentContext
            .servlet(new ServletContainer(new YourResourceConfig()))
            .addListener(ContextLoaderListener.class)
            .contextParam("contextConfigLocation", "classpath:applicationContext.xml")
            .build();
}
Stela answered 15/8, 2016 at 2:37 Comment(1)
Found there is an equivalent answer here. But sadly new problem appeared... That is, when used with jersey-spring3 (to integrate with Spring Framework), no dependency will be found. Still trying to find the solution.Stela
D
0

I had a similiar problem and solved it with a test container factory.

public class SessionRestTest extends JerseyTest {

    @Override
    protected TestContainerFactory getTestContainerFactory() {
        // standard servername and port is localhost:9998
        return new GrizzlyWebTestContainerFactory();
    }

    @Override
    protected DeploymentContext configureDeployment() {
        ResourceConfig config = new ResourceConfig(SessionRest.class);
        return ServletDeploymentContext.forServlet(
                new ServletContainer(config)).build();
    }

    private Response get() {
        return target("/session/logout").request().get();
    }

    @Test
    public void testRedirectURL() {
        Response response = get();
        assertEquals("should return status 200", HttpStatus.OK_200, response.getStatus());
    }

}
Dexterdexterity answered 26/7, 2021 at 13:12 Comment(0)
O
-1

The easier way is to provide correct factory in a test constructor:

TestSomeResource() {
    super(new GrizzlyWebTestContainerFactory());
}

and provide servlet context:

@Override
protected DeploymentContext configureDeployment() {
    return ServletDeploymentContext.forPackages("...").build(); // or other builder method
}
Orthodoxy answered 29/1, 2016 at 13:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.