简体   繁体   中英

Jersey rest test fails because of session inside of resource method

I have Jersey rest api, but when I try to test it it fails because of I am getting session data there, so the questions is, how can I mock or ignore this session variable, which Jersey can't detect?

Here is a request from my test:

User response = target("/am/users/" + userId).request().get(new GenericType<User>() { });

Here is my resource:

@GET
@Path("{userId}")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public User getUser(@PathParam("userId") String userId, @Context HttpServletRequest request) {
    User supportUser = (User)request.getSession().getAttribute("USER"); // Here is where it fails.
    User user = userDao.getUser(userId, supportUser);
    return user;
}

The problem is that the Jersey test is not running inside a servlet environment, which is something that is required to work with the servlet APIs. If you are not aware, Jersey does not need to run inside a servlet container. If the case of using the provider-grizzly2 , if you don't set up the test container, it will default to running the GrizzlyTestContainerFactory , which only starts Grizzly and an HTTP server, not a servlet container.

In order to configure the JerseyTest as a servlet container, we need to override two other methods, configurDeployment and getTestContainerFactory . With the latter, we need to return the GrizzlyWebTestContainerFactory , which will set up the servlet container. In the configureDeployment method, we can configure the application, at the servlet level.

public class ServletTest extends JersyTest {

    @Override
    public ResourceConfig configure() {
        // configure Jersey
    }

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

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

If you are using the provider-inmemory , it doesn't support servlet deployment, so you will need to switch over to the jetty provider or the grizzly provider.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM