FluentAssertions, making sure IEnumerable contains only single element
Asked Answered
F

3

6

I am writing unit tests and I have something that looks like this:

[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?
}

And GetFoos() returns and IEnumerable<Foo>

Footed answered 20/7, 2015 at 20:8 Comment(1)
What do you mean "doesn't work"? Please clarify the questionPilsner
S
7

OnlyContain expects a predicate -

 GetFoos().Should().OnlyContain(x => _foo1.Equals(x));
Showroom answered 20/7, 2015 at 20:35 Comment(0)
B
6

With 6.7.0 version of FluentAssertions you can use :

_sut.GetFoos()
    .Should().ContainSingle()
    .Which.Should().Be(_foo1);
Beria answered 15/9, 2022 at 9:23 Comment(0)
U
-2

Try this page as see if it helps. 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.
Urethrectomy answered 20/7, 2015 at 20:17 Comment(4)
This doesn't directly address the question.Showroom
It shows different ways of getting results without giving the answer directly. Thanks for the down vote. Much appreciated.Urethrectomy
Im serious though, maybe I should have been more specific.Urethrectomy
@EricBowser your answer was good but you need to add an explanation for the uninitiated just a quick one liner explaining what one or more of those lines are doing would have been great (sort that and I will up vote you buddy)Lave

© 2022 - 2024 — McMap. All rights reserved.