Assert to compare two lists of objects C#

前端 未结 3 816
梦谈多话
梦谈多话 2021-01-14 17:13

I am currently trying to learn how to use unit testing, and I have created the actual list of 3 animal objects and the expected list of 3 animal objects. The question is how

3条回答
  •  臣服心动
    2021-01-14 17:26

    I am of the opinion that implementing the IEqualityComparer (Equals() and GetHashCode()) for only testing purpose is a code smell. I would rather use the following assertion method, where you can freely define that on which properties you want to do the assertions:

    public static void AssertListEquals(Action asserter, IEnumerable expected, IEnumerable actual)
    {
        IList actualList = actual.ToList();
        IList expectedList = expected.ToList();
    
        Assert.True(
            actualList.Count == expectedList.Count,
            $"Lists have different sizes. Expected list: {expectedList.Count}, actual list: {actualList.Count}");
    
        for (var i = 0; i < expectedList.Count; i++)
        {
            try
            {
                asserter.Invoke(expectedList[i], actualList[i]);
            }
            catch (Exception e)
            {
                Assert.True(false, $"Assertion failed because: {e.Message}");
            }
        }
    }
    

    In action it would look like as follows:

        public void TestMethod()
        {
            //Arrange
            //...
    
            //Act
            //...
    
            //Assert
            AssertAnimals(expectedAnimals, actualAnimals);
        }
    
        private void AssertAnimals(IEnumerable expectedAnimals, IEnumerable actualAnimals)
        {
            ListAsserter.AssertListEquals(
                (e,a) => AssertAnimal(e,a),
                expectedAnimals,
                actualAnimals);
        }
    
        private void AssertAnimal(Animal expected, Animal actual)
        {
            Assert.Equal(expected.Name, actual.Name);
            Assert.Equal(expected.Weight, actual.Weight);
            //Additional properties to assert...
        }
    

    I am using XUnit for the simple Assert.True(...) and Assert.Equals(), but you can use any other unit test library for that. Hope it helps someone! ;)

提交回复
热议问题