1

Using FluentAssertions, I want to check a list only contains objects with certain values.

For example, I attempted to use a lambda;

myobject.Should().OnlyContain(x=>x.SomeProperty == "SomeValue");            

However, this syntax is not allowed.

Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55
djnz
  • 109
  • 1
  • 14
  • I found a way of achieving this but not sure if there is a better way; myobject.Select(x=>x.SomeProperty ).Should().Equal("SomeValue") – djnz Jul 06 '15 at 10:06

1 Answers1

3

I'm pretty sure that should work. Check out this example unit test from FluentAssertions' GitHub repository:

    [TestMethod]
    public void When_a_collection_contains_items_not_matching_a_predicate_it_should_throw()
    {
        //-----------------------------------------------------------------------------------------------------------
        // Arrange
        //-----------------------------------------------------------------------------------------------------------
        IEnumerable<int> collection = new[] { 2, 12, 3, 11, 2 };

        //-----------------------------------------------------------------------------------------------------------
        // Act
        //-----------------------------------------------------------------------------------------------------------
        Action act = () => collection.Should().OnlyContain(i => i <= 10, "10 is the maximum");

        //-----------------------------------------------------------------------------------------------------------
        // Act
        //-----------------------------------------------------------------------------------------------------------
        act.ShouldThrow<AssertFailedException>().WithMessage(
            "Expected collection to contain only items matching (i <= 10) because 10 is the maximum, but {12, 11} do(es) not match.");
    }
Mariano Desanze
  • 7,847
  • 7
  • 46
  • 67
Dennis Doomen
  • 8,368
  • 1
  • 32
  • 44