FluentAssertions;合并集合和对象图比较断言

时间:2016-06-17 14:24:59

标签: c# unit-testing fluent-assertions

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

我有以下课程。

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.EqualsShould I be using IEquatable to ease testing of factories?

3 个答案:

答案 0 :(得分:2)

从文档和我使用框架的经验来看,它确实使用了@foreach (var item in Model) { <p> @item.FirstName @item.Surname @item.Gender.GenderDesc </p> }

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

以下示例说明如何确保集合仅包含特定的object.Equals对象,并断言集合不包含特定对象。

Contract

答案 1 :(得分:1)

您可以覆盖合同Equals,然后使用该合同,您的单元测试应该会愉快地通过。 如果您使用的是随机Guids,则可能会出现问题,但您似乎正在使用预定义的。

尝试以下内容:

protected bool Equals(Contract other)
{
    return Id.Equals(other.Id) && string.Equals(Name, other.Name);
}

public override bool Equals(object obj)
{
    if (ReferenceEquals(null, obj)) return false;
    if (ReferenceEquals(this, obj)) return true;
    if (obj.GetType() != this.GetType()) return false;
    return Equals((Contract) obj);
}

public override int GetHashCode()
{
    unchecked
    {
        return (Id.GetHashCode()*397) ^ (Name != null ? Name.GetHashCode() : 0);
    }
}

正如您所看到的,它通过了测试: enter image description here

答案 2 :(得分:1)

除了Nkosi's回答之外,您仍然可以通过构建预期来使用$.fn.changeTextField = function (value) { return $(this).val(value).trigger("change"); }

相关问题