Hello, Today I am going to tell you about RestAssured’s hidden feature. This is JSON Schema validator. You can also validate your XML schemas by using the same approach.
Testing endpoints is a straightforward process but sometimes you need to go deeper and check if some other stuff is working or not. A developer might change a property of an endpoint that would not affect your test. But this part might break some other part of your application because of inconsistency.
We had this problem in a project so we decided to implement JSON validation in our automated tests to get fast feedback about the structure of our endpoints.
Which library to use?
In order to do schema validation, you need to add JSON Schema Validator library into your project. You may find the details of the library in this link(https://mvnrepository.com/artifact/io.rest-assured/json-schema-validator/3.0.0).
After adding this library into your project, you will be able to use new hamcrest matchers like;
The usage of these hamcrest matchers is exactly the same if you’re familiar with them. There’s no significant difference.
Response response = given().when()
.header(Bearer, “Authorization blabla")
.body(“This is the body”)
Do not forget to put your JSON file into the resource folder of your project. If not, you’ll get a “file not found exception”. In case you don’t what to use matchesJsonSchemaInClasspath, you can use matchesJsonSchema method that would let to give a different kind of input types like String, InputReader, File etc…
But how do you get the JSON Schema of an endpoint? That’s something your developers might provide or you can produce by using online services like https://jsonschema.net/.
If you know your example response from Swagger or from a previous test execution. Just copy paste this result into this website and get your JSON Schema.
After running the test, in case your schema matches the predefined one, your test execution will pass. In case there’s a failure you’ll find all the details about the failure in the console.