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

后端 未结 10 1748
日久生厌
日久生厌 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:59

    I recommend against using reflection or anything complex, it just adds more work/maintenace.

    Serialize the object (i recommend json) and string compare them. I'm unsure why you object to order by but I'd still recommend it as it will save a custom compare's for each type.

    And it automatically works with domain objects change.

    Example (SharpTestsEx for fluent)

    using Newtonsoft.Json;
    using SharpTestsEx;
    
    JsonConvert.SerializeObject(actual).Should().Be.EqualTo(JsonConvert.SerializeObject(expected));
    

    You can write it as a simple extensions and make it more readable.

       public static class CollectionAssertExtensions
        {
            public static void CollectionAreEqual(this IEnumerable actual, IEnumerable expected)
            {
                JsonConvert.SerializeObject(actual).Should().Be.EqualTo(JsonConvert.SerializeObject(expected));
            }
        }
    

    and then using your example call it like so:

    var foundCollection = fooManager.LoadFoo();
    var expectedCollection = new List() 
    {
        new Foo() { Bar = "a", Bar2 = "b" },
        new Foo() { Bar = "c", Bar2 = "d" }
    };
    
    
    foundCollection.CollectionAreEqual(foundCollection);
    

    You'll get an assert message like so:

    ...:"a","Bar2":"b"},{"Bar":"d","Bar2":"d"}]

    ...:"a","Bar2":"b"},{"Bar":"c","Bar2":"d"}]

    ...__________________^_____

提交回复
热议问题