1
votes

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.

1
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

1 Answers

2
votes

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.");
    }