问题描述
我有一个带有对象类型属性的简单类,该类可以包含从不同来源构建的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在比较期间进行字符串转换吗?
解决方法
[Fact]
public void CompareJson()
{
var jsonText = @"{
""Element1"": 123,""Element2"": ""text""
}";
var x1 = new SimpleClass { Id = "X",JSONData = jsonText };
var x2 = new SimpleClass { Id = "X",JSONData = JsonConvert.DeserializeObject(x1.JSONData.ToString()) };
x1.Should().BeEquivalentTo(
x2,o => o.Using<object>(ctx => ctx.Subject.ToString().Should().Be(ctx.Expectation.ToString())).When(
info => info.SelectedMemberPath.EndsWith(nameof(SimpleClass.JSONData))));
}