使用NJsonSchema在单元测试中解析JSON $ ref

时间:2018-06-04 15:39:40

标签: json unit-testing njsonschema

我已将JSON架构拆分为多个文件,并按标准方式("$ref": http://rootpath/otherfile.json#/definitions/link)按要求引用它们。

JSON文件是项目中的嵌入资源。 rootpath会根据部署的位置发生变化。但是在生产中一切正常(请求获得JSON响应和模式一样,当验证对模式的响应时,NJsonSchema在内部获取参考模式并提取完成验证所需的内容)

然而,在测试方面,这是另一回事。响应很好,并且第一个模式被删除了。 rootpath使得所有内容都与http://testapi/相关,但实际上并不存在。因此,当NJsonSchema尝试获取引用模式时,它会查找http://testapi/otherfile.json#/definitions/link之类的内容,这显然会失败。

从阅读this我想我想要使用重载来获取允许我指定JsonReferenceResolver的JsonSchema4对象,然后我可以在生产中使用默认值并注入我的拥有一个用于测试,以便它在我控制并将存在的某个地方寻找$ref。但我无法看到任何文档或示例。

示例模式:

{ // 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" ]
        }
    }
}

回复示例:

{
    "schema": "http://testapi/schemas/root.json",
    "link": { "rel": "self", "href": "http://testapi/root" }
};

验证码(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);
...

1 个答案:

答案 0 :(得分:1)

我指定JsonReferenceResolver的预感是在右边。在上面的例子中,我无法从root.json获得对common.json的引用,以及&#39; work&#39;在测试环境中,因为在那种环境中服务/路径不存在。

因此,在设置环境时,我确实知道common.json是什么,即我知道它的内容为字符串,因此可以将其作为模式(JsonSchema4 commonSchema = JsonSchema4.FromJsonAsync(commonJsonAsString).Result;)。

使用这个我可以设置一个参考解析器工厂&#39;并在其中添加一个文档引用,以便http://testapi/schemas/common.json#/...的所有引用都从我的commonSchema获得,即

private Func<JsonSchema4, JsonReferenceResolver> referenceResolverFactory;
this.referenceResolverFactory = x =>
{
    JsonSchemaResolver schemaResolver = new JsonSchemaResolver(x, new JsonSchemaGeneratorSettings());
    JsonReferenceResolver referenceResolver = new JsonReferenceResolver(schemaResolver);
    referenceResolver.AddDocumentReference("http://testapi/schemas/common.json", commonSchema);

    return referenceResolver;
};

可以通过以相同方式添加更多文档引用来解决不同的引用。

然后,当我尝试转换root.json模式(使用它对common.json的引用)或另一个模式(引用common.json)时,我使用了FromJsonAsync的重载,它传入referenceResolverFactory

private bool GetAndValidateResponse(string schemaName, string response, string schemaAsString)
{
    // schemaName:     Name of the schema being validated, e.g. "root.json"
    // response:       http response body as a string, see 'Example response' in question
    // schemaAsString: The schema being validate as a string, e.g. root.json contents in question
    //
    // Check the response object against the schema
    JsonSchema4 schema = JsonSchema4.FromJsonAsync(schemaAsString, schemaName, this.referenceResolverFactory).Result;
    ICollection<ValidationError> errors = schema.Validate(response);

    return errors.Count < 1;
}

在我的单元测试的情况下,我只对它是否有效感兴趣,因此布尔返回值。如果您对确切的错误感兴趣,显然可以退回该集合。

此外,我每个单元测试类只设置一次工厂,而不是每次测试。但是,对于模式中的每个ref,它都会正确地进入工厂。