Jersey 2.x集成Spring,怎么做单元测试

如题所述

这里介绍另一个方法,利用“内存中的容器”来调试,就是我们不用打包并扔到tomcat中,自己在IDE中,用Unit Test的方法来测试。

1. Jersey的测试框架支持的容器很多,这里选用了常用的grizzly2
在项目的pom.xml中,引入依赖:
<dependency>
<groupId>org.glassfish.jersey.test-framework</groupId>
<artifactId>jersey-test-framework-core</artifactId>
<version>${jersey.version}</version>
<scope>test</scope>
</dependency>

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

2. 写Jersey的Resource文件
@Path("my/jersey")
public class TestResource{
@Autowired
protected SystemManager systemManager; //这由spring注入

@GET
@Path("/test")
public String test(@QueryParam("systemId") Integer systemId) {
return "test";
}
}

3. 书写SystemManager和SystemManagerImpl
略

4. 把manager配置到Spring Application.xml中
略

5. 书写Jersey Application
@Path("webapi")
public class TestApplication extends ResourceConfig {
public TestApplication(){
register(RequestContextFilter.class);
register(TestResource.class);
}
}

6. 书写Unit Test文件
public class MyRestTest extends JerseyTest {

@Override
protected Application configure() {
ResourceConfig rc = new MyApplication()
.register(SpringLifecycleListener.class)
.register(RequestContextFilter.class);

enable(TestProperties.LOG_TRAFFIC);
enable(TestProperties.DUMP_ENTITY);

return configure(rc);
}

@Override
protected ResourceConfig configure(ResourceConfig rc) {
rc.property("contextConfigLocation", "spring.xml");
return rc;
}

@Test
public void test(){

final String hello = target("my/jersey/test")
.queryParam("systemId", 1)
.request()
.get(String.class);
System.out.println("==========\n" + hello);
}
}

7. 运行test(),即可看到结果。
温馨提示:答案为网友推荐,仅供参考