请大家帮忙?
泽西 Bug 连接:[1]:https://java.net/jira/browse/JERSEY-2412
当我使用测试提供程序(测试的 jetty 和 grizzly2)时,servlet 请求、响应和上下文没有注入(inject)到类中。 我使用包注释来启动应用程序。
你还有别的办法吗?
public class VMResourceTest extends BaseTest {
@Test
public void testCreateVm() {
String bodyData = loadClassPathData(CLASS_PATH+File.separator+"tools"+File.separator+"createVm.json");
Response response = target("/tool/cloud/vrm/fm/ghca_vms").queryParam("platform_id", "A22A4B0C3AEC49F5916EA8CC01F56E9A")
.request().header("X-Auth-GHCA-User-ID", "X-Auth-GHCA-User-ID")
.post(Entity.entity(bodyData, MediaType.APPLICATION_JSON));
assertEquals("200", response.getStatus());
}
}
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) {}
请求和响应为空。
最佳答案
您需要为 Servlet 环境配置 JerseyTest
。在你的 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
,它会返回一个 ServletDeploymentContext.Builder
。 .如果您查看 Javadoc,您会看到一些看起来很熟悉的方法,例如 initParam(...,...)
、addListener
等。这就像构建您的 web.xml 以编程方式。只需继续链接方法,然后构建。
通过上述配置,您不再需要重写JerseyTest
中的configure
方法。只需像上面看到的那样添加 ResourceConfig
。
查看其他测试示例here
另见相关内容:
关于java - jersey2 单元测试,HttpServletRequest 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29386360/