DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Exploring JSON Schema for Form Validation in Web Components
  • Datafaker Gen: Leveraging BigQuery Sink on Google Cloud Platform
  • Validate XML Request Against XML Schema in Mule 4
  • Validate JSON Request Against JSON Schema in Mule 4

Trending

  • Data Lake vs. Warehouse vs. Lakehouse vs. Mart: Choosing the Right Architecture for Your Business
  • AI-Driven Root Cause Analysis in SRE: Enhancing Incident Resolution
  • Cloud Security and Privacy: Best Practices to Mitigate the Risks
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  1. DZone
  2. Coding
  3. Languages
  4. Structural Validation of JSON Using Rest Assured

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.

By 
Remi Andonissamy user avatar
Remi Andonissamy
·
Apr. 27, 21 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
30.7K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

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 GET, POST, PUT and 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."

Schema/Structure Validation

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:

JSON
 




x
11


 
1
{
2
  "id": 10,
3
  "firstName": "Remi",
4
  "lastName": "Jullian",
5
  "email": "remi.jullian@abc.com",
6
  "programme": "Financial Analysis",
7
  "courses": [
8
    "Accounting",
9
    "Statistics"
10
  ]
11
}



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:

JSON
 




xxxxxxxxxx
1
40


 
1
{
2
  "$schema": "http://json-schema.org/draft-04/schema#",
3
  "type": "object",
4
  "properties": {
5
    "id": {
6
      "type": "integer"
7
    },
8
    "firstName": {
9
      "type": "string"
10
    },
11
    "lastName": {
12
      "type": "string"
13
    },
14
    "email": {
15
      "type": "string"
16
    },
17
    "programme": {
18
      "type": "string"
19
    },
20
    "courses": {
21
      "type": "array",
22
      "items": [
23
        {
24
          "type": "string"
25
        },
26
        {
27
          "type": "string"
28
        }
29
      ]
30
    }
31
  },
32
  "required": [
33
    "id",
34
    "firstName",
35
    "lastName",
36
    "email",
37
    "programme",
38
    "courses"
39
  ]
40
}



Rest Assured Logic To Test the Schema

Step 1: Add a "JSON schema validator" dependency in pom.xml.

XML
 




xxxxxxxxxx
1


 
1
        <dependency>
2
            <groupId>io.rest-assured</groupId>
3
            <artifactId>json-schema-validator</artifactId>
4
            <version>3.0.0</version>
5
        </dependency>



Step 2: Add a "hamcrest-all" dependency for asserting the JSON schema.

XML
 




xxxxxxxxxx
1


 
1
        <dependency>
2
            <groupId>org.hamcrest</groupId>
3
            <artifactId>hamcrest-all</artifactId>
4
            <version>1.3</version>
5
            <scope>test</scope>
6
        </dependency>



Step 3: Load the expected "schema.JSON" in a file object.

Java
 




x


 
1
File schema = new File(System.getProperty("user.dir")+"schema.json");



Step 4: Fire the rest assured request, validate the response body using the matchesJsonSchema method. 

Java
 




x



1
given().get("http://localhost:8080/student/10").then().body(matchesJsonSchema(schema));



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. 

Full Code

Java
 




xxxxxxxxxx
1
15


 
1
import static io.restassured.RestAssured.*;
2
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchema;
3
import java.io.File;
4
import org.testng.annotations.Test;
5

          
6
public class StructureValidation {
7
    
8
    @Test
9
    public void JSONSchemaValidation() {    
10
        File schema = new File(System.getProperty("user.dir")+"schema1.json");
11
      given().
12
          get("http://localhost:8080/student/10").
13
      then().
14
          body(matchesJsonSchema(schema));      
15
    }



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.  

Conclusion

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.

JSON Schema

Opinions expressed by DZone contributors are their own.

Related

  • Exploring JSON Schema for Form Validation in Web Components
  • Datafaker Gen: Leveraging BigQuery Sink on Google Cloud Platform
  • Validate XML Request Against XML Schema in Mule 4
  • Validate JSON Request Against JSON Schema in Mule 4

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!