rest-assured schema validation (including JSON schema validation and XML Schema validation)

Source: Internet
Author: User
Tags xsd example



Rest-assured supports schema validation starting with version 2.1.0, including JSON schema validation and XML schema validation. We have previously asserted that the response body is a field to assert, so if the asserted field is much more troublesome, in order to solve this problem, we can use the schema file for the response body assertion, the schema file can assert the entire response.



1.JSON Schema Validation



For example: Place the following schema file under classpath , Products-schema.json:


 
 
 1 {
 2     "$schema": "http://json-schema.org/draft-04/schema#",
 3     "title": "Product set",
 4     "type": "array",
 5     "items": {
 6         "title": "Product",
 7         "type": "object",
 8         "properties": {
 9             "id": {
10                 "description": "The unique identifier for a product",
11                 "type": "number"
12             },
13             "name": {
14                 "type": "string"
15             },
16             "price": {
17                 "type": "number",
18                 "minimum": 0,
19                 "exclusiveMinimum": true
20             },
21             "tags": {
22                 "type": "array",
23                 "items": {
24                     "type": "string"
25                 },
26                 "minItems": 1,
27                 "uniqueItems": true
28             },
29             "dimensions": {
30                 "type": "object",
31                 "properties": {
32                     "length": {"type": "number"},
33                     "width": {"type": "number"},
34                     "height": {"type": "number"}
35                 },
36                 "required": ["length", "width", "height"]
37             },
38             "warehouseLocation": {
39                 "description": "Coordinates of the warehouse with the product",
40                 "$ref": "http://json-schema.org/geo"
41             }
42         },
43         "required": ["id", "name", "price"]
44     }
45 }


The schema file above can be used to verify that the response data for the "/products" request conforms to the specification:


 
1 get("/products").then().assertThat().body(matchesJsonSchemaInClasspath("products-schema.json"));


Matchesjsonschemainclasspath is statically imported from the Io.restassured.module.jsv.JsonSchemaValidator class, And it is recommended to statically import all the methods in this class, but in order to be able to use Io.restassured.module.jsv.JsonSchemaValidator This class must rely onjson-schema-validatormodule, we can from this page download It, or add the following dependencies through Maven to get:


<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>3.0.6</version>
</dependency>


1.1 JSON Schema Validation settings



Rest-assured's Json-schema-validator module uses the Francis Galiegue's Json-schema-validator (fge) library to implement validation (Validation). If you want to configure the base Fge library, we can write this:


 
 
1 // Given
2 JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory.newBuilder().setValidationConfiguration(ValidationConfiguration.newBuilder().setDefaultVersion(DRAFTV4).freeze()).freeze();
3 
4 // When
5 get("/products").then().assertThat().body(matchesJsonSchemaInClasspath("products-schema.json").using(jsonSchemaFactory));


This using method allows us to pass a jsonschemafactory instance, which is used by rest-assured when validating. This configuration allows us to make more detailed configuration when validating the response results.



The FGE library also allows setting validation to checked or unchecked, rest-assured checked is used by default, and if you want to change this value, we can provide a An example of jsonschemavalidatorsettings is given to Matcher. For example:


1 get ("/products"). Then (). Assertthat (). Body (Matchesjsonschemainclasspath ("Products-schema.json"). Using (Settings (). with (). Checkedvalidation (false)));


The setting method above is statically imported from the Jsonschemavalidatorsettings class.



1.2 Json Schema Validation static configuration



Let's imagine that if we want to use unchecked's validation all the time and want to set the JSON schema version to 3, instead of providing jsonschemavalidatorsettings instances to all matchers, We might as well define it as a static:


 
 
1 JsonSchemaValidator.settings = settings().with().jsonSchemaFactory(
2         JsonSchemaFactory.newBuilder().setValidationConfiguration(ValidationConfiguration.newBuilder().setDefaultVersion(DRAFTV3).freeze()).freeze()).
3         and().with().checkedValidation(false);
4 
5 get("/products").then().assertThat().body(matchesJsonSchemaInClasspath("products-schema.json"));
 


By the way above, any matcher that imports Jsonschemavalidator now uses DRAFTV3 as the default version and uses unchecked validation.



In order to reset Jsonschemavalidato to the default configuration, we can simply call the reset method to implement:


1 jsonschemavalidato.reset ();


1.3 JSON Schema valition not dependent on rest-assured



We do not rely on rest-assured and we can use json-schema-valition, as long as we represent the JSON file as a String type, we can do this:


 
 
1 import org.junit.Test;
 2 import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
 3 import static org.hamcrest.MatcherAssert.assertThat;
 4  
 5 public class JsonSchemaValidatorWithoutRestAssuredTest {
 6  
 7  
 8     @Test public void
 9     validates_schema_in_classpath() {
10         // Given
11         String json = ... // Greeting response
12  
13         // Then
14         assertThat(json, matchesJsonSchemaInClasspath("greeting-schema.json"));
15     }
16 }


Schema and DTD Validation for 2.Xml (validation)



We can also validate the XML response body by using an XML Schema (XSD) or DTD.



XSD Example:


1 get ("/carrecords"). Then (). Assertthat (). Body (Matchesxsd (XSD));


DTD Example:


1 get ("/videos"). Then (). Assertthat (). Body (MATCHESDTD (DTD));


matchesXsdMethods and matchesDtd methods belong to the Hamcrest matchers package, we need to import the io.restassured.matcher.RestAssuredMatchers statically.



rest-assured schema validation (including JSON schema validation and XML Schema validation)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.