Refactoring: Introduce SetUp Method

Tests in a TestFixture share common initialization code.

Create a method in the TestFixture, move common initialization code to the method, and execute the method prior to each test.   

Before:

[

Test]
public void UponCreationCountIsZero()
{
BookmarkCollection collection = new BookmarkCollection();
Assert.AreEqual(0, collection.Count);
}

[

Test]
public void AddBookmarkCountIsIncremented()
{
BookmarkCollection collection = new BookmarkCollection();
collection.Add("Label", new Uri(https://example.com));
Assert.AreEqual(1, collection.Count);
}

After the Refactoring:

[

TestFixture]
public class BookmarkCollectionFixture
{
private static BookmarkCollection collection;

[

SetUp]
public void BeforeTest()
{
collection = new BookmarkCollection();
}

[

Test]
public void UponCreationCountIsZero()
{
Assert.AreEqual(0, collection.Count);
}

[

Test]
public void AddBookmarkCountIsIncremented()
{
collection.Add("Label", new Uri(https://example.com));
Assert.AreEqual(1, collection.Count);
}
}

The common code in this case is the creation of the BookmarkCollection in each test method. That code is moved to the [SetUp] method. NUnit insures that the method is executed prior to each test being executed.

This example demonstrates the need to keep the test code as clean as the production code. This means that if you see duplication it is your job to remove it, even in the test code. As a side note, I do agree with Brian Button that doing this refactoring does reduce the communication of the test code. His reasoning is that after the refactoring I have to look at the [SetUp] method and the individual [Test] methods to understand the full extent of the tests. This example illustrates the trade-off between removing duplication and code communication. I am interested in hearing opinions on the trade-off in this example and your everyday experience.

Lastly, there is another refactoring, named Introduce TearDown Method which removes common clean-up code from the tests to a method that is executed after the tests are run.