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

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

问题描述

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

我的 rest 服务具有身份验证方法,该方法采用用户名、密码并返回令牌.

我已经为身份验证方法编写了测试用例.但我不确定如何使用 url 进行测试.

公共类 TestAuthenticate {服务服务=新服务();字符串用户名 = "用户";String password = "密码";字符串令牌;@Test(预期 = Exception.class)公共最终无效 testAuthenticateInputs() {密码 = "通行证";service.authenticate(用户名,密码);}@Test(预期 = Exception.class)public final void testAuthenticateException(){用户名 = 空;String token = service.authenticate(username, password);assertNotNull(token);}@测试公共最终无效 testAuthenticateResult() {String token = service.authenticate(username, password);assertNotNull(token);}}

解决方案

如果要使用 URL 进行测试,则需要从测试中启动服务器.您可以显式启动嵌入式服务器,这在测试中很常见.类似的东西

公共类 MyResourceTest {public static final String BASE_URI = "http://localhost:8080/api/";私有 HttpServer 服务器;@前public void setUp() 抛出异常 {最终 ResourceConfig rc = new ResourceConfig(Service.class);服务器 = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);}@后公共无效撕裂()抛出异常{服务器停止();}@测试公共无效测试服务(){客户端客户端 = ClientBuilder.newClient();WebTarget target = client.target(BASE_URI).path(service");...}}

这基本上是一个集成测试.您正在启动 Grizzly 容器并将 ResourceConfig 加载到只有 Service 类的服务器.当然,您可以在配置中添加更多类.您可以使用真实"如果需要,可以进行资源配置.

上面的测试使用了这个依赖

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

我更喜欢的另一种选择是使用 .您可以选择版本,下一页应该有一个链接,可以下载.您可以使用搜索栏搜索其他人.

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

import com.sun.jersey.api.client.WebResource;导入 com.sun.jersey.api.core.DefaultResourceConfig;导入 com.sun.jersey.spi.container.servlet.WebComponent;进口 com.sun.jersey.test.framework.JerseyTest;导入 com.sun.jersey.test.framework.WebAppDescriptor;导入 javax.ws.rs.GET;导入 javax.ws.rs.Path;进口junit.framework.Assert;导入 org.junit.Test;公共类 SimpleTest 扩展 JerseyTest {@Path(服务")公共静态类服务{@得到public String getTest() { return "Hello World!";}}公共静态类 AppConfig 扩展了 DefaultResourceConfig {公共 AppConfig() {超级(服务.类);}}@覆盖公共 WebAppDescriptor 配置(){返回新的 WebAppDescriptor.Builder().initParam(WebComponent.RESOURCE_CONFIG_CLASS,AppConfig.class.getName()).建造();}@测试公共无效 doTest() {WebResource 资源 = 资源().路径(服务");String result = resource.get(String.class);Assert.assertEquals(Hello World!", result);System.out.println(结果);}}

您很可能不会将资源和 ResourceConfig 与测试放在同一个类中,但我只是想让它保持简单并且在一个类中全部可见.

无论您使用的是 web.xml 还是 ResourceConfig 子类(如上所示),您都可以通过使用单独的 ResourceConfig 来减少测试内容,内置测试课,就像我所做的那样.否则,如果您使用的是普通的 ResourceConfig 类,则只需在 configure 方法中替换它即可.

configure 方法几乎只是用 Java 代码构建一个 web.xml 文件.您可以在 WebAppDescriptor.Builder 中看到不同的方法,例如 initParam,它与您的 web 中的 相同xml.您可以简单地在参数中使用字符串,但有一些常量,正如我上面使用的那样.

@Test 是您通常要运行的 JUnit 测试.它正在使用 Jersey 客户端.但不是创建 Client,您只需访问 resource() 方法即可使用预配置的 Client,该方法返回一个 WebResource.如果您熟悉 Jersey Client,那么这门课对您来说应该不陌生.

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.

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);
    }
}

解决方案

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");
        ...
    }
}

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>

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);
    }
}

Using this dependency

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

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.

Some Resources

Some Examples


UPDATE

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);
    }
}

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.

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.

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.

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天全站免登陆