asp.net-core - 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"));
}
解决方案
我找到了一个与JsonDocument.Parse()
检查字符串的有效性一样紧凑的解决方案。json
JsonSerializer
string malformedJson = "345[]{}q345"
JsonSerializer.Deserialize<object>(malformedJson)
然后我能够针对异常进行测试JsonException
而不必担心JsonReaderException
推荐阅读
- sql-server - 防止在另一个 SQL Server 中附加我的本地数据库并防止访问我的数据?
- java - 用户长按时更改android上的任何按钮
- javascript - 在 nodejs express 中处理 Unhandling Promise Rejection
- groovy - 如何在JSR223的Groovy类中使用JMeter的内部方法(vars.get()等)
- react-native - 升级到 react-native 0.59.x 后还可以使用 react-navigation 2.x 吗?
- coldfusion - 在两个页面之间丢失会话变量
- firebase - 是否可以通过 CLI 添加自定义声明?
- angularjs - 隧道服务器离线:请求失败,状态码 502,当我运行 gulp serve 时重试 1 秒
- excel - 如果嵌套 if 语句中的一个或两个单元格为空,如何在一个单元格中返回 0?
- pandas - 与每列的中位数进行比较