![](/img/trans.png)
[英]How to get the the URI path for javax.ws.rs.core.UriInfo with parameters instead of values
[英]How to get instance of javax.ws.rs.core.UriInfo
有没有javax.ws.rs.core.UriInfo
实现,我可以用它来快速创建一个实例进行测试。 这个界面很长,我只需要测试一下。 我不想在这个界面的整个实现上浪费时间。
更新:我想为类似于此的函数编写单元测试:
@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) {
}
}
除了资源类之外,它还可以注入其他提供程序,如ContainerRequestContext
, ContextResolver
, MessageBodyReader
等。
实际上我想为类似于你的doSomthing()函数的函数编写一个junit测试。
我没有在你的帖子中选择那个。 但是我可以想到几个单元测试选项
只需创建一个存根,只实现您使用的方法。
使用像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); }
您需要添加此依赖项
<dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.9.0</version> </dependency>
如果你想进行集成测试,注入实际的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"));
}
}
只需添加此依赖项
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-inmemory</artifactId>
<version>${jersey2.version}</version>
</dependency>
它使用内存容器,这对于小型测试来说效率最高。 如果需要,还有其他具有Servlet支持的容器。 只需看看我上面发布的链接。
你要么嘲笑它,要么使用像http://arquillian.org/这样的东西
我正在编写集成测试,所以不能使用mock东西
我用了一些代码进行球衣测试
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.