Testing Jersey Based REST Services with Grizzly

本文介绍如何利用轻量级Grizzly服务器进行REST服务的单元测试。通过在测试环境中启动Grizzly服务器,并设置必要的初始化参数,可以实现REST资源的直接测试。文章提供了具体的测试示例代码。

原文见:http://thoughts.inphina.com/2011/03/07/testing-rest-with-grizzly/

 

In my last post, we had seen how easy it was to create REST based services with Spring and Jersey. In this post we would quickly see how we can unit test them. Ok, this is not entirely a unit test in the strict sense because we are not testing the resource in isolation but it is a good strategy nevertheless because it helps us to test the resource right from the IDE.

For this, we would include the Grizzly servlet webserver dependency in our pom.xml.

1 <dependency>
2             <groupId>com.sun.grizzly</groupId>
3             <artifactId>grizzly-servlet-webserver</artifactId>
4             <version>1.9.8</version>
5         </dependency>

 

Once we have the Grizzly server, we would have to power it up at the start of our tests so that the resource can execute inside the container. The test start-up would look like this

 

1@Before
2     public void setUp() throws Exception {
3         threadSelector = GrizzlyMain.startServer();
4         ClientConfig clientConfiguration = new DefaultClientConfig();
5         Client client = Client.create(clientConfiguration);
6         webresource = client.resource(GrizzlyMain.baseUri);
7     }

 

Also, at the end of every test, we have to terminate the endpoint so that the port is now available for the next test. Hence, we do

 

1@After
2 public void tearDown() throws Exception {
3     threadSelector.stopEndpoint();
4}

 

If you would notice, we have started the GrizzlyServer with GrizzlyMain.startServer(); Let us see what this class looks like

 

01 public class GrizzlyMain {
02      
03     private static int getPort(int defaultPort) {
04         String port = System.getenv("JERSEY_HTTP_PORT");
05         if (null != port) {
06             try {
07                 return Integer.parseInt(port);
08             catch (NumberFormatException e) {
09             }
10         }
11         return defaultPort;       
12     }
13      
14     final static URI baseUri = UriBuilder.fromUri( "http://localhost/").port( 9998 ).build();
15      
16     public static SelectorThread startServer() throws IOException{
17         final ServletAdapter adapter =new ServletAdapter();
18         adapter.addInitParameter( "com.sun.jersey.config.property.packages","com.inphina.sample" );
19         adapter.addInitParameter("com.sun.jersey.api.json.POJOMappingFeature""true" );
20         adapter.addContextParameter("contextConfigLocation","classpath:applicationContext.xml"  );
21         adapter.addServletListener("org.springframework.web.context.ContextLoaderListener" );
22         adapter.setServletInstance( new SpringServlet() );
23         adapter.setContextPath(baseUri.getPath());
24         adapter.setProperty( "load-on-startup"1 );
25
26         System.out.println("********" + baseUri.getPath());
27         SelectorThread threadSelector = GrizzlyServerFactory.create(baseUri, adapter);
28         return threadSelector;
29     }
30         
31     public static void main(String[] args) throws IOException {
32         System.out.println("Starting grizzly...");
33         SelectorThread threadSelector = startServer();
34         System.out.println(String.format(
35                 "Jersey app started with WADL available at %sapplication.wadl\n" +
36                 "Hit enter to stop it...", baseUri));
37         System.in.read();
38         threadSelector.stopEndpoint();
39     }   
40}

 

As you would notice, the startServer() method, starts the server along with all the details which are present in our web.xml (refer to the last post). Here, we register the SpringServlet and also pass all the init parameters to the servlet. A snapshot of the web.xml is shown here

 

01 <servlet>
02         <servlet-name>REST</servlet-name>
03         <servlet-class>
04             com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
05         <init-param>
06             <param-name>com.sun.jersey.config.property.packages</param-name>
07             <param-value>com.inphina.social.resources</param-value>
08         </init-param>
09         <init-param>
10             <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
11             <param-value>true</param-value>
12         </init-param>
13         <load-on-startup>1</load-on-startup>
14     </servlet>

 

Now, let us look at a sample test

 

1@Test
2     public void getOnHelloWorldPath() {
3         // get the initial representation
4         String s = webresource.path("helloworld").accept("application/json").get(String.class);
5         Assert.assertEquals("{\"name\":\"Vikas Hazrati\",\"age\":36,\"email\":\"vhazrati@inphina.com\"}", s);
6         System.out.println(s);
7     }

 

Here, we make a GET call at the path helloworld and expect a JSON string to be returned which should be equal to what we are expecting. Likewise to make a sample post call you would have a method like this

 

01@Test
02     public void testPostLoginJSONFormat() {
03         User user = new User();
04         user.setEmail("admin");
05         user.setPassword("admin");
06         Address address = new Address();
07         address.setStreet("123");
08         user.addAddress(address);
09
10         webresource.path("helloworld").type("application/json").post(user);
11         Assert.<something>
12     }

 

Hence, it is easy to test the REST services with the lightweight Grizzly server in place. Thecomplete code for this and previous post can be accessed here.

http://justrest.googlecode.com/svn/trunk/ justrest-read-only

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值