【发布时间】:2021-01-11 10:34:59
【问题描述】:
我有一个简单的类,它有一个对象类型的属性,它可以包含从不同来源构建的 JSON
public class SimpleClass
{
public string Id { get; set; }
public object JSONData { get; set; }
}
我正在使用 FluentAssertions 对象图比较,但这不起作用
private void Verify(SimpleClass actualOutput, SimpleClass expectedOutput)
{
actualOutput.Should().BeEquivalentTo(expectedOutput);
}
根据对象的来源,我看到类似这样的消息
Expected member JSONData to be a
System.Collections.Generic.IDictionary`2[System.String,Newtonsoft.Json.Linq.JToken], but found a
System.Text.Json.JsonElement.
Expected member JSONData to be
System.String, but found
System.Text.Json.JsonElement.
当我将它们转换为字符串时,对象是相等的
private void Verify(SimpleClass actualOutput, SimpleClass expectedOutput)
{
actualOutput.JSONData.ToString().Should().Be(expectedOutput.JSONData.ToString());
}
我不想像那样比较单个属性,因为我需要比较 SimpleClass 实例的集合。有没有办法使用对象图比较来完成这项工作?我可以配置 FluentAssertions 在比较期间进行字符串转换吗?
【问题讨论】:
-
你试过什么?什么不起作用?
-
您的序列化程序不匹配。
Newtonsoft.Json和System.Text.Json。无论如何,要正确处理这种情况,请将所有 JSON 反序列化为强类型值并比较结果
标签: c# json .net unit-testing fluent-assertions