0

I wanted to mock HttpServletRequest object which is placed into Jersey resource class. I am extending JerseyTest class.

package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.glassfish.jersey.test.DeploymentContext;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.ServletDeploymentContext;
import org.glassfish.jersey.test.TestProperties;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
import static javax.ws.rs.core.Response.Status.OK;

@RunWith(MockitoJUnitRunner.class)
public class CopyAuthResourceV2ApiTest extends JerseyTest {

    private ObjectMapper objectMapper;

    @Path("base")
    public static class AuthResource {

        @Context
        private HttpServletRequest request;

        @GET
        @PermitAll
        @Path("fetch")
        @Consumes(APPLICATION_JSON)
        @Produces(APPLICATION_JSON)
        public Response fetchUser(@QueryParam("id") String id) {

            HttpSession session = request.getSession(false); // need to mock

            if (session != null) {
                Object o = session.getAttribute(id); // need to mock
                return Response.status(OK)
                        .entity(o)
                        .build();
            }

            return Response.status(INTERNAL_SERVER_ERROR)
                    .entity("Internal server error.")
                    .build();
        }
    }

    @Provider
    public static class DebugMapper implements ExceptionMapper<Throwable> {
        public Response toResponse(Throwable e) {
            e.printStackTrace();
            return Response.serverError().build();
        }
    }

    @Override
    protected DeploymentContext configureDeployment() {
        objectMapper = new ObjectMapper();
        objectMapper.findAndRegisterModules();

        enable(TestProperties.LOG_TRAFFIC);
        ResourceConfig config = new ResourceConfig(AuthResource.class, DebugMapper.class);

        return ServletDeploymentContext.forServlet(new ServletContainer(config))
                .build();
    }

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

    @Test
    public void asd() {
        Response response = target("base/fetch").queryParam("id", "testId").request().cookie(new Cookie("JSESSIONID", "42rFCUx8EhBeB15mXH8iY7_YEwmv4hIE_oVkymVC")).get();
    }
}

I tried mock that dependency like thats articles propose:

Link 1 Link 2 Link 3

but with no results. I am using Jersey test framework with jersey-test-framework-provider-grizzly2 and jersey-container-grizzly2-servlet.

HttpServletRequest should return HttpSession object which has mocked getAttribute method. Does anyone knows solutions for that problem?

akaras
  • 54
  • 1
  • 7
  • Sessions are determined by the cookie JSESSIONID. So to get an initial cookie, you need to make an initial request to get that session. I don't know where you are doing that. Then when you get the response, you need to extract the cookie and send it back out with the next request. The JAX-RS client has all of these capabilities. Just do some googling. – Paul Samsotha Sep 24 '19 at 08:16
  • @PaulSamsotha i have edited @Test method once more time, but i have no problem with doing request. I need to mock `HttpServletRequest` object and I am asking how to do it. – akaras Sep 24 '19 at 08:22
  • Use Mockito or make your own stub by implementing the interface. You can either use Mockito to inject the instance of the resource class or you can object the request through constructor instead of field. That way you can create an instance of the resource passing the mock. And the register the instance with the ResourceConfig. – Paul Samsotha Sep 24 '19 at 21:56

0 Answers0