如果 FluentAssertions 中的 AssertionScope 失败,如何在第一行插入消息?

问题描述 投票:0回答:1

我正在循环访问结果数组,并将每个对象与预期结果数组进行比较

resultItem.Should().BeEquivalentTo(expectedResultItem)
。每个项目都有一个唯一的标识符并希望将其显示在上面。

这是一个示例结果,前两行来自 BeEquivalentTo 的单次调用,而第三个条目来自不同的调用:

Expected property resultItem.PropertyA to be "85.01", but "85.00" differs near "0" (index 4).
Expected property resultItem.PropertyB to be 85.01M, but found 85.00M.
Expected step to be MyProject.Models.ResultItem
{
    IdA = "620",
    IdB = "Total", 
    PropertyA = "12156.00", 
    PropertyB = 12156.0M, 
    PropertyC = 33
}, but found <null>.

是否可以在每个结果上方插入更多详细信息作为某种形式的标题?像这样的东西:

Error found on entry (IdA:12, IdB: "ABC")
Expected property resultItem.PropertyA to be "85.01", but "85.00" differs near "0" (index 4).
Expected property resultItem.PropertyB to be 85.01M, but found 85.00M.
Error found on entry (IdA:620, IdB: "Total")
Expected step to be MyProject.Models.ResultItem
{
    IdA = "620",
    IdB = "Total", 
    PropertyA = "12156.00", 
    PropertyB = 12156.0M, 
    PropertyC = 33
}, but found <null>.
c# .net-core xunit fluent-assertions
1个回答
1
投票

虽然这不是“理想”的可读性,但您可以滥用 FA 的 because 参数来让它输出一些上下文:

[TestMethod]
public void AssertionContext()
{
  using (new AssertionScope())
  {
    Foo resultItem = new Foo { PropA = "123.0", PropB = 123.0m, Id = 777 };
    resultItem.Should().BeEquivalentTo(new { PropA = "123.1", PropB = 123.1m }, "ID {0} should match", resultItem.Id);

    Foo step = null;
    step.Should().BeEquivalentTo(new Foo { PropA = "123.0", PropB = 123.0m }, "ID {0} should match", 987654);
  }
}

Expected property resultItem.PropA to be "123.1" because ID 777 should match, but "123.0" differs near "0" (index 4).
Expected property resultItem.PropB to be 123.1M because ID 777 should match, but found 123.0M.
Expected step to be Foo
{
    Id = 0, 
    PropA = "123.0", 
    PropB = 123.0M
} because ID 987654 should match, but found <null>.
© www.soinside.com 2019 - 2024. All rights reserved.