How to assert that two list contains elements with the same public properties in NUnit?

后端 未结 10 1745
日久生厌
日久生厌 2021-02-04 02:20

I want to assert that the elements of two list contains values that I expected, something like:

var foundCollection = fooManager.LoadFoo();
var expectedCollectio         


        
10条回答
  •  无人及你
    2021-02-04 03:07

    No, NUnit has no such mechanism as of current state. You'll have to roll your own assertion logic. Either as separate method, or utilizing Has.All.Matches:

    Assert.That(found, Has.All.Matches(f => IsInExpected(f, expected)));
    
    private bool IsInExpected(Foo item, IEnumerable expected)
    {
        var matchedItem = expected.FirstOrDefault(f => 
            f.Bar1 == item.Bar1 &&
            f.Bar2 == item.Bar2 &&
            f.Bar3 == item.Bar3
        );
    
        return matchedItem != null;
    }
    

    This of course assumes you know all relevant properties upfront (otherwise, IsInExpected will have to resort to reflection) and that element order is not relevant.

    (And your assumption was correct, NUnit's collection asserts use default comparers for types, which in most cases of user defined ones will be object's ReferenceEquals)

提交回复
热议问题