Do Repeat Yourself in Unit Tests

Don’t get me wrong I’m a big supporter of the DRY (Don’t Repeat Yourself) Principle except however when it comes to unit tests. Why? Well, in my opinion a unit test should be a self-contained group of actions with the intent to test a very specific piece of code and should not depend on externals shared with other unit tests.

In a typical unit test we can divide its code in two major groups:

  • Preparation of preconditions for the code under test;
  • Invocation of the code under test.

It’s in the first group that you are tempted to refactor common code in several unit tests into helper methods that can then be called in each one of them. Another way to not duplicate code is to use the built-in infrastructure of some unit test frameworks such as SetUp/TearDown methods that automatically run before and after each unit test.

I must admit that in the past I was guilty of both charges but what at first seemed a good idea since I was removing code duplication turnout to offer no added value and even complicate the process when a given test fails.

We love unit tests because of their rapid feedback when something goes wrong. However, this feedback requires most of the times reading the code for the failed test. Given this, what do you prefer? To read a single method or wander through several methods like SetUp/TearDown and private common methods.

I say it again, do repeat yourself in unit tests. It may feel wrong at first but I bet you won’t regret it later.

Advertisements

2 thoughts on “Do Repeat Yourself in Unit Tests”

  1. Totally agree! Ideally, a test should be a self-contained, complete story, so that if it fails, it’s completely obvious where it is failing. Have you looked into xUnit.Net (http://xunit.codeplex.com) ? It’s a testing framework, which is going for “less is more”, and for instance, they purposely removed the Setup/Teardown feature, precisely for the reasons you mention…

    1. In practice I never used xUnit to implement unit tests, but I remember checking it out and I completely agree with that philosophy. IIRC, they also pioneered the Assert.Throws method which was much more powerful and correct than the ExpectedException attribute available at the time in NUnit and other frameworks.

      If it weren’t for the fact that NUnit has also introduced this feature and several others I would probably already switched to xUnit.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s