Are Too Many Assertions a Code Smell?

assertionscode smellcode-qualitytddtesting

I've really fallen in love with unit testing and TDD – I am test infected.

However, unit testing is normally used for public methods. Sometimes though I do have to test some assumptions-assertions in private methods too, because some of them are "dangerous" and refactoring can't help further. (I know, testing frameworks allow testing private methods).

So it became a habit of mine that the first and the last line of a private method are both assertions.

However, I've noticed that I tend to use assertions in public methods (as well as the private) just "to be sure". Could this be "testing duplication" since the public method assumptions are tested from the outside by the unit testing framework?

Could someone think of too many assertions as a code smell?

Best Answer

Those assertions are really useful for testing your assumptions, but they also serve another really important purpose: documentation. Any reader of a public method can read the asserts to quickly determine the pre and post conditions, without having to look at the test suite. For this reason, I recommend you keep those asserts for documentation reasons, rather than testing reasons. Technically you are duplicating the assertions, but they serve two different purposes and are very useful in both.

Keeping them as asserts is better than simply using comments, because they actively check assumptions whenever they are run.