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

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

    Simple code explaining how to use the IComparer

    using System.Collections;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    
    namespace CollectionAssert
    {
        [TestClass]
        public class UnitTest1
        {
            [TestMethod]
            public void TestMethod1()
            {
                IComparer collectionComparer = new CollectionComparer();
                var expected = new List{ new SomeModel { Name = "SomeOne", Age = 40}, new SomeModel{Name="SomeOther", Age = 50}};
                var actual = new List { new SomeModel { Name = "SomeOne", Age = 40 }, new SomeModel { Name = "SomeOther", Age = 50 } };
                NUnit.Framework.CollectionAssert.AreEqual(expected, actual, collectionComparer);
            }
        }
    
        public class SomeModel
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
    
        public class CollectionComparer : IComparer, IComparer
        {
            public int Compare(SomeModel x, SomeModel y)
            {
                if(x == null || y == null) return -1;
                return x.Age == y.Age && x.Name == y.Name ? 0 : -1;
            }
    
            public int Compare(object x, object y)
            {
                var modelX = x as SomeModel;
                var modelY = y as SomeModel;
                return Compare(modelX, modelY);
            }
        }
    }
    

提交回复
热议问题