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

后端 未结 10 1744
日久生厌
日久生厌 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 02:55

    I had a similar problem. Listing contributors, which contains "commenters" and other ppl... I want to get all the comments and from that derive the creators, but I'm ofc only interested in unique creators. If someone created 50 comments I only want her name to appear once. So I write a test to see that the commenters are int the GetContributors() result.

    I may be wrong, but what I think your after (what I was after when I found this post) is to assert that there are exactly one of each item in one collection, found in another collection.

    I solved this like so:

    Assert.IsTrue(commenters.All(c => actual.Count(p => p.Id == c.Id) == 1));
    

    If you also want the resulting list not to contain other items than expected you could just compare the length of the lists as well..

    Assert.IsTrue(commenters.length == actual.Count());
    

    I hope this is helpful, if so, I'd be very grateful if you would rate my answer.

提交回复
热议问题