首页 > 解决方案 > JsonDocument 解析 JsonReaderException - xUnit

问题描述

我以为我找到了一种更清洁的方法,占地面积更小,可以测试 astring是否有效JSON;但是,当我运行测试时它失败了,因为它返回 aJsonReaderException所以当我尝试将类型更改为此时,我收到一个保护错误,因为它似乎是内部的?

System.Text.Json在我的项目中使用。

如何更改它以便我可以使用现有代码:

    public ApplicationSettings WithTemplate(string template) {

    try {
        JsonDocument.Parse(template);
        baseTemplate = template;
    }
    catch(JsonException ex) {
        throw ex;
    }
    return this;
}

测试代码:

[Fact]
public void WithTemplate_ThrowsJsonExceptionWhenBaseTemplateIsInvalid() {
    Assert.Throws<JsonException>(() => new ApplicationSettings()
                                    .WithTemplate("345[]{}q345"));

}

标签: asp.net-corexunit

解决方案


我找到了一个与JsonDocument.Parse()检查字符串的有效性一样紧凑的解决方案。jsonJsonSerializer

string malformedJson = "345[]{}q345"

JsonSerializer.Deserialize<object>(malformedJson)

然后我能够针对异常进行测试JsonException而不必担心JsonReaderException


推荐阅读