【问题标题】:FluentAssertions - Check equivalency but ignore properties on source onlyFluentAssertions - 检查等效性但仅忽略源上的属性
【发布时间】:2021-12-22 23:26:33
【问题描述】:

给定 2 种具有不同属性的不同对象类型,X 类和 Y 类:

X (Source) Y (Destination)
AA A
B B
C C
D

映射后,我尝试比较属性的等效性,如下所示:

  • X.B 应该等于 Y.B,否则失败
  • X.C 应该等于 Y.C,否则失败
  • X.D 应该被忽略并且不会导致任何失败,因为 Y 不会 包含“D”
  • Y.A 应该会导致失败,因为 X 不包含 'A'

使用 FluentAssertions 我可以得到非常接近的结果:

Y.Should().BeEquivalentTo(X, options => options.ExcludingMissingMembers());

这里唯一的问题是最后一个标准将不被满足:YA将被忽略(因为我们需要在这里测试失败,因为目标具有源上不存在的属性,因此没有被映射)。

【问题讨论】:

  • “它应该失败”是什么意思?它永远不能被映射到,不是吗?那么,它失败或不失败的条件是什么?
  • 在这种情况下,永远不会映射正确的“A”。所以条件是,由于 X 没有“A”(但 Y 有),它应该会失败。换句话说,Destination 的 fail 具有 Source 没有的属性。
  • 您是否为此使用了一些映射器库?

标签: c# fluent-assertions


【解决方案1】:

我可能无法理解您要声明的所有规则。但是你特别提到了一件事:

Y.A 将被忽略(因为我们需要在这里测试失败

public class X
{
    public string AA { get; set; }
    public string B { get; set; }
    public string C { get; set; }
    public string D { get; set; }
}

public class S
{
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }
}

[Fact]
public void Test1()
{
    X s = new X();
    S d = new S();

    s.Should().BeEquivalentTo(d, options => options.IncludingProperties());
}

此测试失败并出现以下错误:

Expectation has property s.A that the other object does not have.

希望这能回答你的问题,或者至少让你更接近一点。

您可以在此处阅读有关使用的 FluentAssertion Api 的更多信息: FluentAssertion docs

链接中有更多配置断言的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多