Testing JSON REST Service with rest assured; Given, When, Then
In my last post, we went over getting started with rest-assured. Now that we have everything set up, I'd like us to take a look at a few more examples of using Rest-Assured to test JSON REST services.
Preferred rest-assured BDD like Syntax
First I got a comment on my previous post from Johan Haleby, the founder of Rest-Assured (ßhow cool is that?!), who told me that the example I featured in my first post was the older way of writing tests.
He reminded me that the preferred and current way is to use the newer BDD (Behavior Driven Development) like given-when-then syntax. This is actually better for the framework that I'm creating, since we're also using BDD with Thucydides. So using the newer syntax will actually make our API tests look similar to our UI tests.
The Given/When/Then structure
When you create BDD features, the majority of its scenarios will be made up of three main Gherkin keywords: Given, When and Then. Each one has a particular function:
- Given = a context/Getting a system in a particular state
- When = something happens/Poke it
- Then =we expect some outcome/examine the new state
Let's take a look at the example from the last post and change it to use the newer syntax:
New Given-When-Then Example
I think using the newer syntax is a big improvement on the readability of the test.
Verifying multiple then values
Besides being able to verify one key value pair in the JSON response, we can also verify multiple values. Say for example we wanted to verify that the status code we get back is 200, which would indicate that the request succeeded, the status shows publish, and the author name equals gebdd.
Using these criteria, our tests will now look like the following:
One important thing to notice is that in order to obtain the name value, we used the dot notation (author.name) to navigate to the nested value we wanted in the JSON response. So, let's say you wanted to obtain the value contained in the self key. In that case you would use: author.meta.links.self
(I just want to point out that in the above example, the equalTo and containsString are examples of hamcrest matchers.)
Rest-Assured supports other requests
Rest-Assured also supports the following requests:
Stay tuned for more REST-Assured posts as we work our way through some POST requests in the next article.
- The Cucumber Book: Behavior-Driven Development for Testers and Developers
- BDD in Action – Behavior-driven development for the whole software lifecycle