Gunjan Doshi

Startups, Entrepreneurship, Agility, Management & Leadership, Metrics

Number of asserts per test - Single Claim Principle

December 4th, 2004 by gunjandoshi

How many asserts can I have per test? Multiple? Only one?

I feel that the number of asserts per test is not the goal. Goal is to use test-driven development to generate value producing simple code. To achieve that goal, if I have to use multiple asserts per test, I am ok with it.

Ward Cunningham originally wanted to call unit tests as claims. Using that lingo, each unit test should make one claim about the expected behavior under some conditions.

For e.g., in the code below

[Test]
public void ParseName() {
EmailParser parser = new EmailParser();
Assert.IsNotNull(parser);
string name = parser.ExtractName(”johndoe@yahoo.com”);
Assert.AreEqual(”johndoe”, name);
}

I am making two different claims:
1. Parser is created properly.
2. The extract functionality is working fine.

Now, as a general rule, if I have one unit test failing, I want only one thing to fix. However, in the case above, if the first assert fails, we may have a hidden problem, as the second assert is not executing.

Other problem is the violation of a basic OO principle. A test is also a first class citizen. Like any good OO class or method, it should have only one responsibility. In other words, it should be making only one claim.

I could write the same test as two different tests:

[Test]
public void CreateParser() {
EmailParser parser = new EmailParser();
Assert.IsNotNull(parser);
}

[Test]
public void ExtractName() {
EmailParser parser = new EmailParser();
string name = parser.ExtractName(”johndoe@yahoo.com”);
Assert.AreEqual(”johndoe”, name);
}

Now, I am making sure that each test is making only one claim. Of course, I will eliminate the duplication later.

However, there may be scenarios when I may have to include multiple asserts per test. I am ok with it as long as each test satisfies the single claim principle. A classic example is the case of triangulation. If I use triangulation to generalize my code, I have two asserts per test.

Tags: No Comments

Leave a Comment

0 responses so far ↓

There are no comments yet...Kick things off by filling out the form below.