如何获取javax.ws.rs.core.UriInfo的实例

是否有任何javax.ws.rs.core.UriInfo实现,我可以用它来快速创建一个实例进行测试。 这个界面很长,我只需要测试一下。 我不想在这个界面的整个实现上浪费时间。

更新:我想为类似于此的函数编写unit testing:

 @GET @Path("/my_path") @Produces(MediaType.TEXT_XML) public String webserviceRequest(@Context UriInfo uriInfo); 

您只需使用@Context注释将其作为字段或方法参数注入。

 @Path("resource") public class Resource { @Context UriInfo uriInfo; public Response doSomthing(@Context UriInfo uriInfo) { } } 

除了您的资源类之外,它还可以注入其他提供程序,如ContainerRequestContextContextResolverMessageBodyReader等。

编辑

实际上我想为类似于你的doSomthing()函数的函数编写一个junit测试。

我没有在你的post中选择那个。 但我可以想到几个unit testing选项

  1. 只需创建一个存根,只实现您使用的方法。

  2. 使用像Mockito这样的Mocking框架,并模拟UriInfo 。 例

     @Path("test") public class TestResource { public String doSomthing(@Context UriInfo uriInfo){ return uriInfo.getAbsolutePath().toString(); } } [...] @Test public void doTest() { UriInfo uriInfo = Mockito.mock(UriInfo.class); Mockito.when(uriInfo.getAbsolutePath()) .thenReturn(URI.create("http://localhost:8080/test")); TestResource resource = new TestResource(); String response = resource.doSomthing(uriInfo); Assert.assertEquals("http://localhost:8080/test", response); } 

    您需要添加此依赖项

      org.mockito mockito-all 1.9.0  

如果你想进行集成测试,注入实际的UriInfo,你应该看看Jersey Test Framework

这是泽西测试框架的完整示例

 public class ResourceTest extends JerseyTest { @Path("test") public static class TestResource { @GET public Response doSomthing(@Context UriInfo uriInfo) { return Response.ok(uriInfo.getAbsolutePath().toString()).build(); } } @Override public Application configure() { return new ResourceConfig(TestResource.class); } @Test public void test() { String response = target("test").request().get(String.class); Assert.assertTrue(response.contains("test")); } } 

只需添加此依赖项

  org.glassfish.jersey.test-framework.providers jersey-test-framework-provider-inmemory ${jersey2.version}  

它使用内存容器,这对于小型测试来说效率最高。 如果需要,还有其他具有Servlet支持的容器。 只需看看我上面发布的链接。

你要么嘲笑它,要么使用像http://arquillian.org/这样的东西

我正在编写集成测试,所以不能使用mock东西

我用了一些代码进行jersey测试

http://www.programcreek.com/java-api-examples/index.php?source_dir=JerseyTest-master/jersey-tests/src/test/java/com/sun/jersey/impl/uri/UriPathHttpRequestTest.java

 WebApplicationImpl wai = new WebApplicationImpl(); ContainerRequest r = new TestHttpRequestContext(wai, "GET", null, "/mycontextpath/rest/data", "/mycontextpath/"); UriInfo uriInfo = new WebApplicationContext(wai, r, null); myresources.setUriInfo(uriInfo); 

 private static class TestHttpRequestContext extends ContainerRequest { public TestHttpRequestContext( WebApplication wa, String method, InputStream entity, String completeUri, String baseUri) { super(wa, method, URI.create(baseUri), URI.create(completeUri), new InBoundHeaders(), entity); } } 

如果您收到有关请求范围bean的任何错误,请参阅spring测试中的请求范围bean