I'm new to unit testing and I want to test some jersey services in a project. We are using Junit. Please guide me to write test cases in better way.
CODE:
@GET @Path("/getProducts/{companyID}/{companyName}/{date}") @Produces(MediaType.APPLICATION_JSON) public Object getProducts(@PathParam("companyID") final int companyID, @PathParam("date") final String date, @PathParam("companyName") final String companyName) throws IOException { return productService.getProducts(companyID, companyName, date); }
Above mentioned service is working fine and I want to write junit test case to test above mentioned method. Above method will retrieve list of products (List<Product>
) in JSON format. I would like to write test case to check response status and json format.
NOTE: We are using Jersey 1.17.1 version.
Help would be appreciated :)
For Jersey web services testing there are several testing frameworks, namely: Jersey Test Framework (already mentioned in other answer - see here documentation for version 1.17 here: https://jersey.java.net/documentation/1.17/test-framework.html) and REST-Assured (https://code.google.com/p/rest-assured) - see here a ...
For Jersey web services testing there are several testing frameworks, namely: Jersey Test Framework (already mentioned in other answer - see here documentation for version 1.17 here: https://jersey.java.net/documentation/1.17/test-framework.html) and REST-Assured (https://code.google.com/p/rest-assured) - see here a comparison/setup of both (http://www.hascode.com/2011/09/rest-assured-vs-jersey-test-framework-testing-your-restful-web-services/).
I find the REST-Assured more interesting and powerful, but Jersey Test Framework is very easy to use too. In REST-Assured to write a test case "to check response status and json format" you could write the following test (very much like you do in jUnit):
package com.example.rest; import static com.jayway.restassured.RestAssured.expect; import groovyx.net.http.ContentType; import org.junit.Before; import org.junit.Test; import com.jayway.restassured.RestAssured; public class Products{ @Before public void setUp(){ RestAssured.basePath = "http://localhost:8080"; } @Test public void testGetProducts(){ expect().statusCode(200).contentType(ContentType.JSON).when() .get("/getProducts/companyid/companyname/12345088723"); } }
This should do the trick for you... you can verify JSON specific elements also very easily and many other details. For instructions on more features you can check the very good guide from REST-Assured (https://code.google.com/p/rest-assured/wiki/Usage). Another good tutorial is this one http://www.hascode.com/2011/10/testing-restful-web-services-made-easy-using-the-rest-assured-framework/.
HTH.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With