C# Unit Testing – Using Custom Asserts in Unit Tests

cdomain-driven-designunit testing

I asked a question on here earlier and Laiv shared the following link.

In the article; it is stated that Eric Evans avoids .equals methods on Entities.

In this question; the accepted answerer talks about using Custom Assertions for Unit Testing rather than .equals

Therefore I am looking at custom assertions. I have created the following class, which compares two products:

public static bool IsSameDescription(Product product1, Product product2)
        {
            // Check for null values and compare run-time types.
            if (product1 == null || product2==null)
                return false;

            return (product1.description == product2.description);
        }

Therefore I can do this in the Unit Test:

Assert.AreEqual(expectedProduct, actualProduct);

What is I wanted to compare two lists of products? I could use a .equals method and then do this:

CollectionAssert.AreEqual(expectedProductList, actualProductList);

How would I implement this? I could implement a static function that accepts two lists and compares them. However, CollectionAssert would not use it? Would it? (because it uses .equals behind the scenes) How can I do this?

Best Answer

To apply the same method to a collection, you can use LINQ to great effect.

If you want to compare everything to the same instance you can do this:

productList.Select(item => IsSameDescription(productA, item)).ToList();

The CollectionAssert also has a variant that takes a comparator function:

CollectionAssert(expectedProductList, actualProductList, IsSameDescription);

Clarification about custom exceptions:

The primary reason to use custom assertions rather than the generic AssertTrue or Assert.IsTrue is that the error messages provide more detail as to what exactly the problem was. For example, Assert.AreEqual(obj1, obj2) or Assert.That(obj1).IsEqualTo(obj2) will tell you both what the expected answer was and what the actual value was. That should be the goal you are looking for with any custom assertion.

There are several assertion libraries, so you might have to re-invent the wheel. Some test libraries have the assertion library included (Like NUnit, JUnit, etc.).

I would much rather see intelligent use of a standard assertion library than writing custom assertions for everything. Using the example you provided:

Assert.AreEqual(product1.Description, product2.Description);

Is as expressive as you need.