Monday, September 29, 2014

Web Service Testing Example



package testingWS;

import groovyx.net.http.ContentType;

import org.junit.Before;
import org.junit.Test;

import com.jayway.restassured.RestAssured;
import com.jayway.restassured.path.json.JsonPath;
import com.jayway.restassured.response.Response;

import static com.jayway.restassured.RestAssured.expect;
import static com.jayway.restassured.RestAssured.get;
import static com.jayway.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.*;


public class TestingUsingRestAssured {

 @Before
   public void setUp(){
    //  do something
   }



@Test
public void testUserFetchesSuccess() {
expect().
body("id", equalTo(12)).
body("firstName", equalTo("Tim")).
body("lastName", equalTo("Tester")).
when().
get("/abc/users/id/12");
}


@Test
   public void testGetProducts(){
       expect().statusCode(200).contentType(ContentType.JSON)
       .when().get("/abc/users/id/1");
   }



// testing a simple response containing some JSON data
@Test
public void testGetSingleUser() {
 expect().
   statusCode(200).
   body(
     "firstName", equalTo("Tim"),
     "lastName", equalTo("Testerman"),
     "id", equalTo(1)).
   when().
   get("/abc/users/single-user");
}

@Test
public void testGetSingleUse1r() {
given().
pathParam("id",1).
expect().
statusCode(200).
body("id", equalTo(1),
"firstName", equalTo("Tim")).

when().
get("/abc/users/id");
}




//we’re using JsonPath to programatically test the returned JSON structure we’re
//using JsonPath to programatically test the returned JSON structure
@Test
public void testGetSingleUserProgrammatic() {

  Response res = get("/abc/users/single-user");

  assertEquals(200, res.getStatusCode());

  String json = res.asString();
  JsonPath jp = new JsonPath(json);

  assertEquals("Tim", jp.get("firstName"));
  assertEquals("Testerman", jp.get("lastName"));
  assertEquals(1, jp.get("id"));
}







// handling basic authentication
// Response Status: 401 Unauthorized/ 200 Status Ok (when logged in with username=admin and password=admin)
/* @Test
public void testAuthenticationWorking() {
  // we're not authenticated, service returns "401 Unauthorized"
  expect().
    statusCode(401).
  when().
  get("/abc/users/secure/person");
  // with authentication it is working
  expect().
    statusCode(200).
  when().
    with().
      authentication().basic("admin", "admin").
  get("/abc/users/secure/person");
}*/


/* @Test
public void testCreateuser() {
  final String firstName = "Tim";
  final String lastName = "Tester";

  given().
    parameters(
      "firstName", firstName,
      "lastName", lastName).
  expect().
    body("firstName", equalTo(firstName)).
    body("lastName", equalTo(lastName)).
  when().
  get("/abc/users/create");
}*/

}

No comments:

Post a Comment