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);
}
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 :
Create a Separate Test for each assert.
Use Parameterized Tests.
If you want to read more about it parameterized testsUse 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)