Testing Jersey Based REST Services with Grizzly

原文见: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\":\"[email protected]\"}", 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

 

猜你喜欢

转载自reason2003.iteye.com/blog/1610001
今日推荐