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
andgetTestContainerFactory
. With the latter, we need to return theGrizzlyWebTestContainerFactory
, which will set up the servlet container. In theconfigureDeployment
method, we can configure the application, at the servlet level.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.