We can get a json schema for any of our json response by going to this website.
https://www.liquid-technologies.com/online-json-to-schema-converter
We can them save that json schema into a file word file named schema.json and put it in our project.
Then to validate that our responses have same schema as this schema file we need to add the following dependency to our pom.xml file
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>4.3.1</version>
<scope>test</scope>
</dependency>
We then import that class into our project
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchema;
We can then compare the schema of the response to the schema we have saved in the file.
File schema = new File("C:\\workspace\\Module15\\schema.json");
RestAssured.given().contentType(ContentType.JSON).log().all().get("/1").then().body(matchesJsonSchema(schema));
So if for our get request for student no 1 the response schema is not same as the one we defined in schema.json then our test will fail. In the above case our test will pass as schema is same as the one in schema.json file.
Now let us deliberately change schema in schema.json file to fail our test.For that we change data type for id from integer to string in our schema.json file
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"id": {
"type": "string"
},
And then we run our code we check that the test gives this error.It says that in schema validator id type should be string but in actual response we got it is integer .
Expected: The content to match the given JSON schema.
error: instance type (integer) does not match any allowed primitive type (allowed: ["string"])
level: "error"
schema: {"loadingURI":"#","pointer":"/properties/id"}
instance: {"pointer":"/id"}
domain: "validation"
keyword: "type"
found: "integer"
expected: ["string"]
Another way to fail json schema validation is to add an extra field in json schema. We will add extra field named city like this
"programme": {
"type": "string"
},
"city": {
"type": "string"
},
"courses": {
"type": "array",
"items": [
{
"type": "string"
},
{
"type": "string"
}
]
}
},
"required": [
"id",
"firstName",
"lastName",
"email",
"programme",
"city",
"courses"
]
}
Then we run or code we get error like this.It says city is missing from actual response we got from server ,but it is there in schema.json
Expected: The content to match the given JSON schema.
error: object has missing required properties (["city"])
level: "error"
schema: {"loadingURI":"#","pointer":""}
instance: {"pointer":""}
domain: "validation"
keyword: "required"
required: ["city","courses","email","firstName","id","lastName","programme"]
missing: ["city"]