DEV Community

DevByJESUS
DevByJESUS

Posted on

Writing Maintainable Test : Multiple Asserts - Avoid Multiple Asserts

Hello πŸ˜„
Today we continue talking about the advices R. Osherove gives us in his great Book The Art of Unit Testing . Today about Multiple Asserts we will briefly talk about why avoid multiple asserts.

Multiple Asserts for a case

Indeed we see it sometimes , i would say it's us who creates this in our codebase. But There is two cases , firstly look at the code example ( again from the book πŸ˜‰)

[Test]
public void CheckVariousSumResultsOgnoringHigherThan1001()
{
   Assert.AreEqual(3, Sum(1001,1,2));
   Assert.AreEqual(3, Sum (1,1001,2));
   Assert.AreEqual(3, Sum (1,2,1001);
}
Enter fullscreen mode Exit fullscreen mode

If we have used a tool for unit testing we all know that if the first assert Fails , the others 2 will not be execute. So The two cases will be πŸ‘‡

We do not need the outputs of the others asserts

In this case we can just be happy and continue πŸ˜„

We need the outputs of the others Asserts

This is the case that happens sometimes, because each asserts is testing something different of our use case. So when there is an error we can not find exactly in the small world of our use case where the error happens. 😏

Roy's Think

This is what Roy Says:

This applies only when you’re asserting on multiple concerns. It wouldn’t hold if you were testing that you got a person with name X, age Y, and so on, because if one assert failed, you wouldn’t care about the others. But this would be a concern if you’re expecting an action to have multiple end results. For example, it should return 3 and change system state. Each one of these is a feature and should work independently of other features

How To Deal With It

There is three solutions :

  1. Create a Separate Test for each assert.

  2. Use Parameterized Tests.
    If you want to read more about it parameterized tests

  3. Use Try...Catch Block.

The order is in term of usage , the first is better then the second and the second better then the third 😸.

What I think about Them

I do not know if for you it is the same , but me these last days i work thoroughly 😩 on front-end , and for the 2 others solutions it is some kind of hard . So i use everyday the first solution ( Create Separate Test for Each Assert ) and it forces me to respect the Enforcing Test Isolation principles.

πŸ˜„ Thanks for Reading.
By The Grace of JESUS , in the next article about unit testing , we will talk about another aspect of multiple asserts in a unit test , comparing objects.
Best Regards 😊

Top comments (0)