Unit testing jersey Restful Services

后端 未结 3 738
故里飘歌
故里飘歌 2020-12-08 07:21

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:

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 07:34

    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.

提交回复
热议问题