【问题标题】:How to exclude a JSON property from comparison如何从比较中排除 JSON 属性
【发布时间】:2022-11-02 20:44:50
【问题描述】:

如何从FluentAssertions.Json 中的比较中排除 JSON 属性?

JToken token, expectedJson;
token.Should().BeEquivalentTo(expectedJson);
{
  "property1":"value1",
  "property2":"value2",
  "property3":"value3"
}

我想从比较中排除名称为“property2”的属性。这怎么可能?

【问题讨论】:

  • 你读过readme吗?你可能应该配置一些IJsonAssertionOptions<>
  • 你的意思是token.Should().BeEquivilentTo(expectedJson, o=>o.Excluding(p=>p.Property2));
  • IJsonAssertionOptions 接口中没有 Excluding 方法。
  • @AndrejB。你有排除吗?类似于 token.Should().BeEquivalentTo(expectedJson, options => options.For(o => o.Property1).Exclude(o => o.Property2));
  • 我发现使用 net462 有限制。 net462 的 FluentAssertions 没有 BeEquivilentTo 选项的重载。所以,我用另一种方法修复了它。

标签: c# json.net fluent-assertions


【解决方案1】:

我通过对 token 和 expectedJson 的预处理来解决它。

JToken token, expectedJson;
((JValue)expectedJson.SelectToken("property2")).Value = null;
((JValue)token.SelectToken("property2")).Value = null;
token.Should().BeEquivalentTo(expectedJson);

【讨论】:

    【解决方案2】:

    您可以直接测试属性而不是整个对象。

    【讨论】:

    • 这是一个糟糕的答案。单独检查属性并不是很好的未来证明。
    猜你喜欢
    • 2012-04-27
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2017-11-23
    • 1970-01-01
    • 2016-10-11
    相关资源
    最近更新 更多