Java jersey2单元测试,HttpServletRequest为空
请大家帮忙?Java jersey2单元测试,HttpServletRequest为空,java,rest,jersey,Java,Rest,Jersey,请大家帮忙? jersey错误连接:[1]: 当我使用测试提供者(tested jetty和grizzly2)时,servlet请求、响应和上下文没有注入到类中。 我使用packages注释来启动应用程序 你还有别的办法吗 请求和响应为空。您需要为Servlet环境配置JerseyTest。在你的运动衫测试中,你应该有 @Override protected TestContainerFactory getTestContainerFactory() { return new
jersey错误连接:[1]:
当我使用测试提供者(tested jetty和grizzly2)时,servlet请求、响应和上下文没有注入到类中。 我使用packages注释来启动应用程序
你还有别的办法吗
请求和响应为空。您需要为Servlet环境配置
JerseyTest
。在你的运动衫测试中,你应该有
@Override
protected TestContainerFactory getTestContainerFactory() {
return new GrizzlyWebTestContainerFactory();
}
@Override
protected DeploymentContext configureDeployment() {
ResourceConfig config = new ResourceConfig(SessionResource.class);
return ServletDeploymentContext.forServlet(
new ServletContainer(config)).build();
}
如果查看ServletDeploymentContext.forServlet
,它将返回一个。如果您查看Javadoc,您将看到一些熟悉的方法,如initParam(…,…)
,addListener
,等等。这就像以编程方式构建web.xml一样。只要保持链接方法,然后构建
使用上述配置,您不再需要覆盖JerseyTest
中的configure
方法。只需添加ResourceConfig
,如上图所示
参见其他测试示例
另见相关文件:
public class BaseTest extends JerseyTest{
public String CLASS_PATH = "classpath:";
public WebTarget target;
public Client client;
@Override
protected Application configure() {
enable(TestProperties.LOG_TRAFFIC);
enable(TestProperties.DUMP_ENTITY);
ResourceConfig rc = new ResourceConfig().packages("com.ghca.easyview.server.api.resource");
rc.register(SpringLifecycleListener.class);
rc.register(RequestContextListener.class);
rc.property("contextConfigLocation", "classpath:spring/spring-config.xml");
return rc;
}
public String loadClassPathData(String classFilePath){
File schemaContextFile = null;
String result = "";
try {
schemaContextFile = readSchemaFile(classFilePath);
BufferedReader br = new BufferedReader(new FileReader(schemaContextFile));
String s = null;
while((s = br.readLine())!=null){
result = result + "\n" +s;
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
@Component
@Path("tool/cloud/vrm")
public class VMResource extends BaseResource{
@Autowired
private VMService vmService;
@Context
public HttpServletRequest request;
@Context
public HttpServletResponse response;
@POST
@Path("{platform_type}/ghca_vms")
@Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public Response createVm(@PathParam("platform_type") String platformType,
@QueryParam("platform_id") String platformId) {}
@Override
protected TestContainerFactory getTestContainerFactory() {
return new GrizzlyWebTestContainerFactory();
}
@Override
protected DeploymentContext configureDeployment() {
ResourceConfig config = new ResourceConfig(SessionResource.class);
return ServletDeploymentContext.forServlet(
new ServletContainer(config)).build();
}