gpt4 book ai didi

c# - 流利的断言;结合集合和对象图比较断言

转载 作者:太空宇宙 更新时间:2023-11-03 21:10:46 25 4
gpt4 key购买 nike

我正在尝试使用 FluentAssertions 来组合集合和对象图比较断言。

我有以下类(class)。

public class Contract
{
public Guid Id { get; set; }
public string Name { get; set; }
}

在集合中返回,就像这样。

ICollection<Contract> contracts = factory.BuildContracts();

然后我想确保该集合仅包含特定的 Contract对象。

contracts.Should().Contain(new Contract() { Id = id1, Name = "A" });

这行不通,我相信是因为 Contain正在使用 object.Equals而不是对象图比较(由 ShouldBeEquivalentTo 提供)。

我还需要断言该集合不包含特定对象,即

contracts.Should().NotContain(new Contract() { Id = id2, Name = "B" });

有效地给定一个包含未知数量项目的集合,我想确保;它包含许多特定项目,并且不包含许多特定项目。

用FluentAssertions提供的函数可以实现吗?

作为旁注,我不想覆盖 object.Equals出于此处讨论的原因。 Should I be using IEquatable to ease testing of factories?

最佳答案

据我从文档和我使用该框架的经验可以看出,它确实使用了 object.Equals

在这种情况下,我倾向于使用 the collections documentation for v3.0 and higher 中引用的表达式谓词.

以下示例展示了如何确保集合仅包含特定的 Contract 对象,并断言该集合不包含特定对象。

[TestMethod]
public void FluentAssertions_Should_Validate_Collections() {
//Arrange
var id1 = Guid.NewGuid();
var id2 = Guid.NewGuid();

var list = new List<Contract>{
new Contract() { Id = id1, Name = "A" },
new Contract() { Id = Guid.NewGuid(), Name = "B"}
};

var factoryMock = new Mock<IContractFactory>();
factoryMock.Setup(m => m.BuildContracts()).Returns(list);
var factory = factoryMock.Object;

//Act
var contracts = factory.BuildContracts();

//Assert
contracts.Should()
.HaveCount(list.Count)
.And.Contain(c => c.Id == id1 && c.Name == "A")
.And.NotContain(c => c.Id == id2 && c.Name == "B");
}

关于c# - 流利的断言;结合集合和对象图比较断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37884063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com