单位测试jerseyRestful Services

我是unit testing的新手,我想在一个项目中测试一些jersey服务。 我们正在使用Junit。 请指导我以更好的方式编写测试用例。

码:

@GET @Path("/getProducts/{companyID}/{companyName}/{date}") @Produces(MediaType.APPLICATION_JSON) public Object getProducts(@PathParam("companyID") final int companyID, @PathParam("date") final String date, @PathParam("companyName") final String companyName) throws IOException { return productService.getProducts(companyID, companyName, date); } 

上面提到的服务工作正常,我想编写junit测试用例来测试上面提到的方法。 上述方法将以JSON格式检索产品ListList )。 我想编写测试用例来检查响应状态和json格式。

注意:我们使用的是Jersey 1.17.1版本。

帮助将不胜感激:)

对于Jersey Web服务测试,有几个测试框架,即:Jersey Test Framework(已在其他答案中提到 – 请参见此处的1.17版文档: https : //jersey.java.net/documentation/1.17/test-framework.html )和REST-Assured( https://code.google.com/p/rest-assured ) – 请参阅此处两者的比较/设置( http://www.hascode.com/2011/09/rest-assured- vs-jersey-test-framework-testing-your-restful-web-services / )。

我发现REST-Assured更有趣,更强大,但Jersey Test Framework也很容易使用。 在REST-Assured编写测试用例“检查响应状态和json格式”中,您可以编写以下测试(非常类似于您在jUnit中所做的):

 package com.example.rest; import static com.jayway.restassured.RestAssured.expect; import groovyx.net.http.ContentType; import org.junit.Before; import org.junit.Test; import com.jayway.restassured.RestAssured; public class Products{ @Before public void setUp(){ RestAssured.basePath = "http://localhost:8080"; } @Test public void testGetProducts(){ expect().statusCode(200).contentType(ContentType.JSON).when() .get("/getProducts/companyid/companyname/12345088723"); } } 

这应该是你的诀窍……你也可以很容易地validationJSON特定元素和许多其他细节。 有关更多function的说明,您可以查看REST-Assured的非常好的指南( https://code.google.com/p/rest-assured/wiki/Usage )。 另一个很好的教程是http://www.hascode.com/2011/10/testing-restful-web-services-made-easy-using-the-rest-assured-framework/ 。

HTH。

只需忽略注释并编写一个传递所需参数的正常unit testing。 我认为返回的类型通常是“javax.ws.rs.core.Response”…可以使用getEntity()方法。 在这种情况下,使用像Mockito这样的Mock对象框架可能会有所帮助。

你熟悉第26章泽西岛测试框架吗?

 public class SimpleTest extends JerseyTest { @Path("hello") public static class HelloResource { @GET public String getHello() { return "Hello World!"; } } @Override protected Application configure() { return new ResourceConfig(HelloResource.class); } @Test public void test() { final String hello = target("hello").request().get(String.class); assertEquals("Hello World!", hello); } }