I have split my JSON schema into several files and reference them as required in the standard way ("$ref": http://rootpath/otherfile.json#/definitions/link
).
The JSON files are embedded resources within the project. The rootpath
changes depending on where it is deployed. But in production everything works fine (a request is made the JSON response is obtained as is the schema, when validating the response against the schema NJsonSchema internally get the reference schema(s) and extracts what it requires to complete the validation)
When it comes to testing, however, it is a different matter. The response is fine, and get the first schema is stubbed out. The rootpath
is such that everything is relative to http://testapi/
but this doesn't actually exist. So when NJsonSchema attempt to get a reference schema it looks up something like http://testapi/otherfile.json#/definitions/link
, which obviously fails.
From reading this I think I'm wanting to use an overload to get the JsonSchema4
object that allows me to specify the JsonReferenceResolver, then I could use the default in production and inject my own one for testing such that it looks for the $ref
s somewhere that I control and will exist. But I can't see any documentation or examples on this.
Example schemas:
{ // root.json
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "@Model.Root/schemas/root.json",
"title": "Root",
"properties": {
"link": { "$ref": "@Model.Root/schemas/common.json#/definitions/link" }
},
"required": [ "link" ]
}
{ // common.json - different file to the above
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "@Model.Root/schemas/common.json",
"definitions": {
"link": {
"title": "Link",
"type": "object",
"properties": {
"rel": { "type": "string" },
"href": { "type": "string" }
},
"required": [ "rel", "href" ]
}
}
}
Example response:
{
"schema": "http://testapi/schemas/root.json",
"link": { "rel": "self", "href": "http://testapi/root" }
};
Validation code (C#):
using NJsonSchema;
using NJsonSchema.Validation;
...
JsonSchema4 schema = await JsonSchema4.FromJsonAsync(<contents of root.json file>);
string response = "{ ""link"": { ""rel"": ""self"", ""href"": ""http://testapi/root"" } }";
ICollection<ValidationError> errors = schema.Validate(response);
...