FluentAssertions,确保IEnumerable只包含一个元素

本文关键字:包含一 元素 IEnumerable 确保 FluentAssertions | 更新日期: 2023-09-27 18:03:44

我正在编写单元测试,我有一些看起来像这样的东西:

[Fact]
public void GetFoos_only_gets_foo1()
{
    _foo1.included = true; //Foo object
    _foo2.included = false; //Foo object
    _sut.GetFoos().Should().OnlyContain(_foo1); // this doesn't work, is there a specific syntax to use?
}

GetFoos()返回和IEnumerable<Foo>

FluentAssertions,确保IEnumerable只包含一个元素

OnlyContain期望谓词-

 GetFoos().Should().OnlyContain(x => _foo1.Equals(x));

对于6.7.0版本的FluentAssertions,你可以使用:

_sut.GetFoos()
    .Should().ContainSingle()
    .Which.Should().Be(_foo1);

试试这个页面,看看是否有帮助。https://github.com/dennisdoomen/fluentassertions/wiki

collection.Should().ContainSingle();
collection.Should().ContainSingle(x => x > 3);
collection.Should().Contain(8).And.HaveElementAt(2, 5).And.NotBeSubsetOf(new[] {11, 56});
collection.Should().Contain(x => x > 3); 
collection.Should().Contain(collection, 5, 6); // It should contain the original items, plus 5 and 6.