[英]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? 我有Jersey休息api,但是当我尝试对其进行测试时,由于我在那里获取了会话数据而失败,所以问题是,我该如何模拟或忽略该会话变量,而Jersey无法检测到该变量?
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. 问题是Jersey测试不在servlet环境中运行,这是使用servlet API所必需的。 If you are not aware, Jersey does not need to run inside a servlet container.
如果您不知道,Jersey不需要在servlet容器中运行。 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. 如果使用provider-grizzly2 ,那么如果您未设置测试容器,它将默认运行
GrizzlyTestContainerFactory
,它仅启动Grizzly和HTTP服务器,而不启动servlet容器。
In order to configure the JerseyTest
as a servlet container, we need to override two other methods, configurDeployment
and getTestContainerFactory
. 为了将
JerseyTest
配置为servlet容器,我们需要重写另外两个方法, configurDeployment
和getTestContainerFactory
。 With the latter, we need to return the GrizzlyWebTestContainerFactory
, which will set up the servlet container. 对于后者,我们需要返回
GrizzlyWebTestContainerFactory
,它将设置servlet容器。 In the configureDeployment
method, we can configure the application, at the servlet level. 在
configureDeployment
方法中,我们可以在servlet级别配置应用程序。
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. 如果您正在使用
provider-inmemory
,则它不支持servlet部署,因此您将需要切换到jetty提供商或grizzly提供商。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.