Search code examples
c#unit-testingnunitassert

How to "Assert.That()" Items in a List match certain conditions with NUnit?


I'm writing some unit-tests and want to check a result-list.

Here a simple example what i'm doing:

[Test]
public void FilterSomething_Test()
{
    List<MyClass> testdata = new List<MyClass>
    {
        new MyClass { SomeProperty = "expectedValue" },
        new MyClass { SomeProperty = "expectedValue" },
        new MyClass { SomeProperty = "unexpectedValue" },
        new MyClass { SomeProperty = "unexpectedValue" },
        new MyClass { SomeProperty = null },
    }

    List<MyClass> result = FilterSomething(testdata);

    Assert.That(
        result.Where(r => r.SomeProperty == "expectedValue"),
        Has.Exactly(2).Items,
        "Two Items should match this..");
}

Output for failed test:

Two Items should match this..

Expected: exactly 2 items

But was: no items

The output doesn't explain what went wrong.

Explanation: I've got a testdata for multiple tests. This is why I want to check for specific items in each test.

My question:

Is there a way to check for item-counts in a list and get a proper message from NUnit?

Perhaps something like

Assert.That(result, Contains.Exacly(2).Items.Which(i => i.SomeProperty == "expectedValue"))

Solution

  • There is Matches constraint expression dedicated for that. Usage in this case could look like:

    Assert.That(result, 
        Has.Exactly(2).Matches<MyClass>(r => r.SomeProperty == "expectedValue"),
        "Two Items should match this..");