Java, Web and Mobile

Blog

Howto: REST Assured

|
Java|Testing

In my current project, I work in the QA team. One of the questions we had to answer was, “How can we test a REST webservice?”

Let me explain shortly what that webservice provides. The service, we had to test allows users to manage images. Technically we talk about the well-known HTTP functions “GET”, “HEAD”, “PUT”, “POST” and “DELETE”.

We decided to use REST Assured. REST Assured is a Java library that makes testing webservices very easy. It follows the principles of behaviour driven testing. With this approach, every single test has basically a simple given().when().then() structure.

For example, a test for the uploading of images could look like that: given().header(“imagepath”).when().post(“to url”).then().statusCode(201)

Using REST Assured in your project

REST Assured is easy to use. You just need to add the following dependencies to your Maven pom.xml file.

The webservice

Let’s take a look at a part to the implementation of the webservice. With the first method, we get a specific image. The second method provides to upload images.

Testing the post method

Let me first explain how to test the post method. Following the behaviour driven testing design, we have a given header and image path. When we upload the image to a specific url, we expect that the status code is 201. We have two negative cases, as well. First is trying to save an image which already exists. In this case, the status code 409 is expected. In the second negative test case, we try to upload an image with a wrong image type (only .jpg is allowed). The test fails as expected.

After running the test methods, it is important to delete the created image, so there are no problems to run the tests again.

Testing the get method

After we created the image we need for testing in the before method, we can run the following test methods to assure the behaviour which is excepted.

The GET-tests includes several positive and negative test cases. The first thing we test, is to get a specific image. In the negative cases, we assure that a wrong or incomplete url leads to an error.

As seen in the test before, we delete the created resources after running.

Testing the content of the response

REST Assured does not only provide the option to check certain http status codes. We are also allowed to check the content of a http responses. In detail, we want to test that the service scales an image correctly. So, we extract the image of the response and check the height and weight.

Conclusion

REST Assured is a very simple way to test your webservices. It is easy to use, simple to write and for the ones who didn’t write the tests easy to understand.

 

Source: https://github.com/rest-assured/rest-assured/wiki/Usage