Unit Testing – Does Single-Assert Testing Break the DRY Principle?

drytestingunit testing

Whenever I write unit tests I have always tried to have a single assert per test to make debugging easier when tests fail. However as I follow this rule I feel like I am constantly copying the same code in each test and by having more tests it becomes harder to go back to read and maintain.

So does single-assertion testing violate DRY?

And Is there a good rule to follow to find a good balance, like just having one test per method?*

*I realize there probably isn't a one-size fits all solution to this but is there a recommended way to approach this?

Best Answer

Proper unit tests have a naming convention that helps you immediately identify what has failed:

public void AddNewCustomer_CustomerExists_ThrowsException()

This is why you have one assertion per test, so that each method (and it's name) corresponds to the condition that you are asserting.

As you've correctly pointed out, each new test is going to have similar setup code. As with any code, you can refactor the common code into its own method to reduce or eliminate the duplication and make your code more DRY. Some testing frameworks are specifically designed to allow you to put that setup code in one place.

In TDD, no test is YAGNI, because you write tests based only on what you require your code to do. If you don't need it, you won't write the test.

Related Topic