Jersey客户端API vs Jersey测试框架

我是Web服务的新手,想知道Jersey客户端API和泽西测试框架有什么区别?

我想测试我的jerseyREST网络服务端点。 哪个是正确的?

有许多HTTP客户端API(例如Apache HttpClient )。 您需要一个进行客户端测试。 我们需要以某种方式通过HTTP访问我们的服务,因此unit testing需要其中一个API。 由于您已经在使用Jersey,因此Jersey客户端API是一个不错的选择。 一个例子可能看起来像

final String url = "http://stackoverflow.com/questions/27160440/" + "jersey-client-api-vs-jersey-test-framework"; Client client = ClientBuilder.newClient(); WebTarget target = client.target(url); Response response = target.request().accept(MediaType..get(); String html = response.readEntity(String.class); System.out.println(html); response.close(); 

如您所见,客户端API不必调用我们的服务。 它只是HTTP调用的接口,具有“Rest”function。 如果我们想运行自己的服务,我们首先需要将它们部署到容器,无论是完整的服务器/容器,还是某些嵌入式变体。 没有框架,完整的测试可能看起来像

   org.glassfish.jersey.containers jersey-container-grizzly2-http   junit junit 4.9 test   public class SimpleTest { static final String BASE_URI = "http://localhost:8080/myapp/"; static HttpServer server; static Client client; private static HttpServer startServer() { final ResourceConfig resourceConfig = new ResourceConfig() .packages("where.my.resources.are") .register(HelloResource.class); // normally the resource class would not be in the unit test class // and would be in the `where.my.resources.are` package pr sub package return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), resourceConfig); } @Path("hello") public static class HelloResource { @GET public String getHello() { return "Hello World!"; } } @BeforeClass public static void setUpClass() { server = startServer(); client = ClientBuilder.newClient(); } @AfterClass public static void tearDownClass() { server.shutdown(); } @Test public void test() { WebTarget target = client.target(BASE_URI); Response response = target.path("hello").request().get(); String hello = response.readEntity(String.class); assertEquals("Hello World!", hello); response.close(); } } 

Jersey测试框架允许我们更轻松地进行半集成/集成测试,并提供更复杂的容器部署选项。 可以将服务启动到轻量级嵌入式容器(也是不同类型)中,这些容器将在运行unit testing时自动启动和停止。 该框架实际上依赖于Jersey Client API,因此如果您使用该框架,则可以在测试用例中使用Client API。 一个例子

   org.glassfish.jersey.test-framework.providers jersey-test-framework-provider-grizzly2 2.13   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() { Response response = target("hello").request().get(); String hello = response.readEntity(String.class); assertEquals("Hello World!", hello); response.close(); } } 

你可以看到@Test相似之处。 那是因为我们正在使用客户端API。 我们不需要显式配置Client ,因为框架为我们做了这个。

因此,选择实际上取决于您是否要使用Test框架。 无论哪种方式,您都应该知道如何使用Jersey客户端API,因为您将以任何一种方式使用它(除非您决定使用其他HTTTP客户端API,如HttpClient)


阅读更多

  • 客户端API
  • 泽西测试框架