Structural Validation of JSON Using Rest Assured
In this article, we discuss JSON Schema Validation and how Rest Assured can be integrated with BDD frameworks like Cucumber so we can write BDD style code.
Join the DZone community and get the full member experience.Join For Free
Rest Assured is an open-source Java-based library used to test RESTful APIs. Using Rest Assured, we can test XML and JSON-based web services. It behaves like a headless client to access APIs and interact with them. It supports different HTTP methods like
DELETE. It can be integrated with popular testing frameworks like Junit, TestNG, etc.
Rest Assured can be integrated with BDD frameworks like Cucumber and we can write BDD style code. Rest Assured supports the Gherkin syntax (Given/When/Then) making the tests human-readable and easy to understand. Rest Assured is implemented in a language called "Groovy."
Upon receiving a valid HTTP request in the form of URL/URI from the client-side, the server returns a JSON response. Validating the response received from the server is a vital task in API Testing. While we talk about testing the response body, we can break the testing into 3 areas:
- Structural/Schema Validation
- Response Body Validation
- Individual Element Validation
In this article, we will see how to perform Structural or Schema Validation of a JSON response.
Let us consider that this is our Response JSON:
For Schema validation, we need to create a schema for our JSON. This will act as our expected schema for validation. We can manually create the schema or we can use any online JSON schema generators to create our expected schema.
Schema is nothing but a JSON file. It will have only datatype information and the expected keys of the JSON. There won't be any values present in the schema.
The expected schema for the above JSON is seen below:
Rest Assured Logic To Test the Schema
Step 1: Add a "JSON schema validator" dependency in pom.xml.
Step 2: Add a "hamcrest-all" dependency for asserting the JSON schema.
Step 3: Load the expected "schema.JSON" in a file object.
Step 4: Fire the rest assured request, validate the response body using the
matchesJsonSchema method validates the response body matches the structure—data type and the required keys. If there is any mismatch, it will report in the console.
Step 5: Schema validation programmatically is very useful when you have a nested JSON, which is very time consuming if we need to validate manually.
In this article, we discussed JSON structure assertion. Validating the structure of the response JSON programmatically is very useful when you work with complex nested JSON's, where testing manually is very time consuming.
Opinions expressed by DZone contributors are their own.