如何测试Jersey REST Web服务? [英] How to test a Jersey REST web service?

查看:170
本文介绍了如何测试Jersey REST Web服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个Restful Web服务,必须使用JUnit4进行测试。我已经使用Jersey Client编写了一个客户端。但是想知道我是否只能使用junit4来测试我的服务。有人可以至少帮我提供样品。

I have written a Restful Web service and have to test it using JUnit4. I have already written a Client using Jersey Client. But want to know if I can test my service only with junit4. Can someone help me with sample at least.

我的休息服务具有验证方法,该方法获取用户名,密码并返回令牌。

My rest service has authenticate method that takes user name, password and returns a token.

我已经为authenticate方法编写了测试用例。但我不确定如何使用url进行测试。

I have written test case for authenticate method. But I am not sure how to test using url.

public class TestAuthenticate {
    Service service  = new Service();
    String username = "user";
    String password = "password";
    String token;

    @Test(expected = Exception.class)
    public final void testAuthenticateInputs() {
        password = "pass";
        service.authenticate(username, password);
    }

    @Test(expected = Exception.class)
    public final void testAuthenticateException(){
        username = null;
        String token = service.authenticate(username, password);
        assertNotNull(token);
    }

    @Test
    public final void testAuthenticateResult() {
        String token = service.authenticate(username, password);
        assertNotNull(token);
    }
}


推荐答案

如果如果您想使用URL进行测试,则需要从测试中启动服务器。您可以显式启动嵌入式服务器,这对于测试来说非常常见。类似

If you want to test using the URL, then you will need to start a server from your test. You can explicitly start an embedded server, which is pretty common for tests. Something like

public class MyResourceTest {

    public static final String BASE_URI = "http://localhost:8080/api/";
    private HttpServer server;

    @Before
    public void setUp() throws Exception {
        final ResourceConfig rc = new ResourceConfig(Service.class);
        server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);       
    }

    @After
    public void tearDown() throws Exception {
        server.stop();
    }

    @Test
    public void testService() {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(BASE_URI).path("service");
        ...
    }
}

它基本上是一个整合测试。您正在启动Grizzly容器并将 ResourceConfig 加载到仅包含 Service 类的服务器。当然,您可以在配置中添加更多类。如果需要,可以使用真实资源配置。

It's basically an integration test. You're starting the Grizzly container and loading a ResourceConfig to the server with only the Service class. Of course you could add more classes to the configuration. You can use "real" resource config if you wanted.

上述测试使用此依赖关系

The above test uses this dependency

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-grizzly2-http</artifactId>
    <version>${jersey2.version}</version>
</dependency>

另一种选择,我更喜欢的是使用 Jersey测试框架,它将为您启动一个嵌入式容器。测试可能看起来更像

Another option, which is the one I prefer, is to make use of the Jersey Test Framework, which will start an embedded container for you. A test might look something more like

public class SimpleTest extends JerseyTest {

    @Override
    protected Application configure() {
        return new ResourceConfig(Service.class);
    }

    @Test
    public void test() {
        String hello = target("service").request().get(String.class);
    }
}

使用此依赖关系

<dependency>
    <groupId>org.glassfish.jersey.test-framework.providers</groupId>
    <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
    <version>${jersey2.version}</version>
    <scope>test</scope>
</dependency>

嵌入式Grizzly容器将在您的 ResourceConfig <引擎盖下启动/ code>配置。在上面的两个示例中,假设服务类的 @Path 值为 service ,正如您在测试网址中看到的那样。

And embedded Grizzly container will get started under the hood, with your ResourceConfig configuration. In both examples above it is assumed the @Path value for the Service class is service, as you can see in the test URLs.

  • Jersey 2 Test Framework user guide

一些例子

  • How to write Unit Test for this class using Jersey 2 test framework
  • How to in-memory unit test Spring-Jersey
  • Example with Mockito, Test Framework, and Jersey 2
  • Example with Mockito, Test Framework, and Jersey 1

如果您不使用Maven,以下是为Jersey Jersey Fraemwork运行嵌入式Grizzly容器所需的罐子

If you're not using Maven, here are the jars you will need to run an embedded Grizzly container for the Jersey Test Fraemwork

我通常搜索我所有的罐子这里。您可以选择版本,下一页应该有一个链接供下载。您可以使用搜索栏搜索其他人。

I usually search for all my jars here. You can select the version and there should be a link in the next page, to download. You can use the search bar to search for the others.

这是一个简单的运行示例,一旦您拥有所有的罐子

Here's a simple running example, once you have all the jars

import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.core.DefaultResourceConfig;
import com.sun.jersey.spi.container.servlet.WebComponent;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.WebAppDescriptor;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import junit.framework.Assert;
import org.junit.Test;

public class SimpleTest extends JerseyTest {

    @Path("service")
    public static class Service {
        @GET
        public String getTest() { return "Hello World!"; }
    }

    public static class AppConfig extends DefaultResourceConfig {
        public AppConfig() {
            super(Service.class);
        }
    }

    @Override
    public WebAppDescriptor configure() {
        return new WebAppDescriptor.Builder()
                .initParam(WebComponent.RESOURCE_CONFIG_CLASS, 
                           AppConfig.class.getName())
                .build();
    }

    @Test
    public void doTest() {
        WebResource resource = resource().path("service");
        String result = resource.get(String.class);
        Assert.assertEquals("Hello World!", result);
        System.out.println(result);
    }
}

你很可能没有资源和测试在同一个类中的 ResourceConfig ,但我只想保持简单,并且在一个类中都可见。

You're most likely not going to have the resources and ResourceConfig in the same class as the test, but I just want to keep it simple and all visible in one class.

无论您使用的是web.xml还是 ResourceConfig 子类(如上所示),都可以减少你在测试类中使用单独的 ResourceConfig 进行测试,正如我所做的那样。否则,如果您使用的是普通的 ResourceConfig 类,则可以在 configure 方法中替换它。

Whether you are using a web.xml or a ResourceConfig subclass (as shown above), you can cut down what you test by using a separate ResourceConfig, built in the test class, as I have done. Otherwise, if you are using your normal ResourceConfig class, you can just replace it in the configure method.

configure 方法,只是用Java代码构建一个web.xml文件。你可以在 WebAppDescriptor.Builder 中看到不同的方法,比如 initParam ,这与<$ c $相同你的web xml中的c>< init-param> 。你可以简单地在参数中使用字符串,但是有一些常量,就像我上面使用的那样。

The configure method, is pretty much just building a web.xml file, just in Java code. You can see different methods in the WebAppDescriptor.Builder, like initParam, which is the same as an <init-param> in your web xml. You can simply use the string in the arguments, but there are some constants, as I used above.

@Test 你通常会运行JUnit测试吗?它正在使用Jersey客户端。但是,只需访问客户端而不是创建客户端。 > resource()方法,返回 WebResource 。如果您熟悉Jersey客户端,那么这个课程对您来说不应该是新手。

The @Test is you usual JUnit test that will run. It is using the Jersey Client. But instead of creating the Client, you can simply just use the preconfigured Client by just accessing the resource() method, which returns a WebResource. If you are familiar with the Jersey Client, then this class should not be new to you.

这篇关于如何测试Jersey REST Web服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆