问题
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;
}
回答1:
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.
来源:https://stackoverflow.com/questions/37344180/jersey-rest-test-fails-because-of-session-inside-of-resource-method