It's so simple! Testing restful Web Services with rest-assured

Source: Internet
Author: User
Tags baseuri set cookie

Testing Restful Web Services with rest-assured

Reprint Annotated Source: http://www.cnblogs.com/wade-xu/p/4298819.html

Here is a framework for testing RESTful Web service, called rest-assured.

He offers a range of good features like DSL syntax, xpath-validate, file uploads, specification reuse, using proxies, Spring MVC mock module test controllers, etc. Letting you test rest service in Java is as flexible as the dynamic language Ruby, groovy.

Table of Contents       1. Prerequisites       2. Configuration       3. Example detailed
4. Troubleshooting 5. Reference source

Pre-conditions
    • JDK >= 1.6
    • Maven 3

Configure the MAVEN project Pom file as follows

<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>rest-assured</artifactId>
<version>2.3.3</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>

Example

A) test a GET Request method,

Request Url:http://10.46.28.193:8080/service/v1/user/login

Return JSON content as follows

{"    UserInfo": {        "password": null,        "userId": "Wadexu",        "Accesssecuritycodes": "10000000000000000000 ",        " FirstName ":" Wade ",        " LastName ":" Xu ",        " status ": 8,        " Officephone ":" 58730 ",        " email ":" [email Protected] ",        " HomePhone ":" 123 "    },    " Success ": True,    " error ": null}

The test code is as follows:

  @Before public    void SetUp () {        restassured.baseuri= "http://10.46.28.193";        Restassured.port = 8080;        Restassured.basepath = "/service/v1";    }    @Test public    void Testuserlogin () {      expect ().        StatusCode ($).        Body (          "Success", Equalto (True),          "Userinfo.userid", Equalto ("Wadexu"),          "Userinfo.firstname", Equalto ("Wade"),          "Userinfo.lastname", Equalto ("Xu"),          "error", Equalto (null)).        When ().        Get ("/user/login?username=wadexu&password=nzrmrcifiw4=");    }

Note that the parameters I requested here are directly in the URL, and I'll show you how to specify the parameters later.

b) How to use the JSON path

Or with the above example, the test code is as follows:

@Test public    void Testuserlogin_jsonpath () {        Response Response = Get ("/user/login?username=wadexu& Password=nzrmrcifiw4= ");        Assertequals (Response.getstatuscode ());        String json = response.asstring ();        JsonPath JP = new JsonPath (JSON);        Assertequals ("Wadexu", Jp.get ("Userinfo.userid"));        Assertequals ("Wade", Jp.get ("Userinfo.firstname"));        Assertequals ("Xu", Jp.get ("Userinfo.lastname"));        Assertequals ("123", Jp.get ("Userinfo.homephone"));    

c) How to use parameters

Get request is with Queryparam, if you write param directly, in this case can also, Rest assured will automatically determine the parameter type (query or form parameter), in some cases, Put or Post you have to refer to Parameter Types

@Test Public voidTestuserlogin_parameter () {FinalString userName = "Wadexu"; FinalString password = "nzrmrcifiw4=";        Given (). Queryparam ("UserName", UserName). Queryparam ("Password", password).                Expect (). StatusCode (200). Body ("Success", Equalto (true),                       "Userinfo.userid", Equalto ("Wadexu"),                       "Userinfo.firstname", Equalto ("Wade"),                       "Userinfo.lastname", Equalto ("Xu"),                       "Error", Equalto (NULL) . When (). Get ("/user/login"); }

In addition, some POST request URLs are followed by parameters, so you can write

Post ("/reserve/{hotelid}/{roomnumber}", "My Hotel", 23);

Or

given ().        Pathparam ("Hotelid", "My Hotel").        Pathparam ("Roomnumber"). When().         Post ("/reserve/{hotelid}/{roomnumber}"). Then         () ...

D) to look at a POST request, this time to request the body of the message, the request body is the JSON body as follows:

{
"CustomerId": "CDICC",
"Broker": "Test",
"Edituserid": "Wadexu"
}

Test code:

@Test Public voidtestcreate () {FinalString bodystring = "{\" customerid\ ": \" cdicc\ ", \" Broker\ ": \" test\ ", \" edituserid\ ": \" Wadexu\ "}";        Given (). ContentType ("Application/json").        Request (). Body (bodystring).          Expect (). StatusCode (200). Body ("Order.ordernumber", is (number.class),          "Order.deletedate", is (Nullvalue ()),"Success", Equalto (true)).        When (). Post ("/order"); }

This is in addition to the request (). Body

and added a header. Request message Header--ContentType

There are many methods of set Headers, one of which you can do as follows:

Given (). Header ("Content-type", "Application/json") given (). Headers ("Accept", "Application/json", " Content-type "," Application/json ")

Note also that the expected results of comparison is not, there are some methods of org.hamcrest.Matchers, because the order number each time different, can not judge the specific how much, so to see whether it is the numbers on the line, Delete date is null value

Hamcrest. A variety of matching device in the Matchers children's shoes can be studied, it is helpful to test the assertion.

Reprint Annotated Source: http://www.cnblogs.com/wade-xu/p/4298819.html

e) Also you can verify HTTP Status code

Because I need to content-type=application/json this service, and my case is not assigned to ContentType, so the return will be an error 415

The server refused this request because the request entity was in a format does supported by the requested resource for the Requested method.

@Test Public voidTestopenorder_error () {FinalString ordernumber = "3017"; FinalString orderversion = "1"; FinalString Versiontype = ""; FinalString Edituserid = ""; FinalString customerId = ""; FinalString state = "";        Given (). Parameters ("OrderNumber", OrderNumber,"Orderversion", Orderversion,"Versiontype", Versiontype,"Edituserid", Edituserid,"CustomerId", CustomerId,"State", State).          Expect (). StatusCode (415).        When (). Post ("/order/open"); }

f) Cookies are actually very similar.

First no set cookie results thrown 403

"Name": "Forbidden",
"Detail": "The request was a legal request, and the server is refusing to respond to it." Unlike a 401 unauthorized response, authenticating'll make no difference. "

@Test  Public void TestCookie () {  expect ().    StatusCode (403).  When ().  Get ("/access");   Given ().    Cookies ("UserName", "Wadexu").  Expect ().    StatusCode ($).  When ().  Get ("/access");}

g) authentication

If your service requires authentication, you need to set the authentication ()

Otherwise 401 --Unauthorized

@Test  Public void testauthentication () {  expect ().    StatusCode (401).  When ().  Get ("/service/user"  expect ().    StatusCode ($).  When ().    With ().      Authentication (). Basic ("Wadexu", "123456").  Get ("/service/user");}

H) specification Reuse specification Reuse

@Test Public voidTestspecreuse () {Responsespecbuilder builder=NewResponsespecbuilder (); Builder.expectstatuscode (200); Builder.expectbody ("Userinfo.userid", Equalto ("Wadexu")); Builder.expectbody ("Userinfo.firstname", Equalto ("Wade")); Builder.expectbody ("Userinfo.lastname", Equalto ("Xu")); Builder.expectbody ("Success", Equalto (true)); Responsespecification Responsespec=Builder.build (); //Use this specification for test example--aexpect ().        Spec (RESPONSESPEC).        When (). Get ("/user/login?username=wadexu&password=nzrmrcifiw4="); //Now re-use for another example – c that returns similar datagiven (). Queryparam ("UserName", "Wadexu"). Queryparam ("Password", "nzrmrcifiw4=").            Expect ().        Spec (RESPONSESPEC).        When (). Get ("/user/login"); }

If you have more tests, returning the desired results and similar, you can continue to use specification to achieve the purpose of reuse.

Reprint Annotated Source: http://www.cnblogs.com/wade-xu/p/4298819.html

The test run results are as follows (without each of the above use cases):

Troubleshooting

Some classes require static imports

Refer to my following:

ImportOrg.junit.Before;Importorg.junit.Test;Import Staticorg.junit.assert.*;Importcom.jayway.restassured.RestAssured;ImportCom.jayway.restassured.builder.ResponseSpecBuilder;ImportCom.jayway.restassured.path.json.JsonPath;ImportCom.jayway.restassured.response.Response;Importcom.jayway.restassured.specification.ResponseSpecification;Import Staticcom.jayway.restassured.restassured.*;Import StaticOrg.hamcrest.Matchers.equalTo;Import Staticorg.hamcrest.matchers.*;

Set your request URL path, default http://localhost:8080

Refer to my base path (that is, so the same section before the request URL) is configured as follows:

@Before      Public void setUp () {        Restassured.baseuri= "http://10.46.28.193";         = 8080;         = "/service/v1";    }

"Warning:cannot find parser for content-type:text/json-using default parser."

– Need to register the relevant parser:e.g. Restassured.registerparser ("Text/json", Parser.json);

Reference sources

Official Document: https://code.google.com/p/rest-assured/

The first article of the goat, thanks for reading, if you think the content of this article is helpful to your study, you can click the recommended button at the bottom right. Your encouragement is my creative power, I wish you all aspects of the work and life of the goat smug!

It's so simple! Testing restful Web Services with rest-assured

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.