Testing with Rest Assured
February 1, 2020
I wanted to have some tests that operated at the HTTP level, and to run these during my Spring Boot application build process.
The following pattern can be used to run these types of tests and to check the results that have been returned from the web service:
import static io.restassured.RestAssured.given; import static io.restassured.RestAssured.when; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.parsing.Parser; import io.restassured.response.Response; //... Response response = given().header("authorization", testBearerToken).when().contentType(ContentType.JSON) .get(DiaryConstants.BASE_URL + "/stores/" + storeId + "/" + calendarDate + "/day-view-admin/"); response.prettyPeek(); // print the response to stdout // Assert response.then().statusCode(200); response.then().assertThat().body("startOfDayMinutes", Is.is(480)); response.then().assertThat().body("endOfDayMinutes", Is.is(1080)); response.then().assertThat().body("rooms.size()", Is.is(2)); response.then().assertThat().body("rooms[0].roomName", Is.is("Room 1")); response.then().assertThat().body("rooms[0].roomId", Is.is((int) rooms.get(0).getId())); response.then().assertThat().body("rooms[0].roomVersion", Is.is((int) rooms.get(0).getVersion())); response.then().assertThat().body("rooms[0].resourceName", Is.is(IsNull.nullValue())); response.then().assertThat().body("rooms[0].resourceId", Is.is(IsNull.nullValue())); response.then().assertThat().body("rooms[1].roomName", Is.is("Room 2")); response.then().assertThat().body("rooms[1].roomId", Is.is((int) rooms.get(1).getId())); response.then().assertThat().body("rooms[1].roomVersion", Is.is((int) rooms.get(1).getVersion())); response.then().assertThat().body("rooms[1].resourceName", Is.is(IsNull.nullValue())); response.then().assertThat().body("rooms[1].resourceId", Is.is(IsNull.nullValue()));
To pass a payload to the service:
final String payload = "{ \"code\":\"REST_TEST\", \"name\":\"Test Store\", \"active\": true }"; given().header("authorization", testBearerToken).when().body(payload).contentType(ContentType.JSON) .post(DiaryConstants.BASE_URL + "/stores").prettyPeek().then().statusCode(200);