Testing and the Single Responsibility Principle
An Example
Maintainability is one important aspect of creating successful tests, however, also feedback is extremely important. When you create automated tests, what you want to achieve in the end is to build a system that will notify you about any problems as early as possible: you increase the feedback loop, basically. Instead waiting for some human tester to provide you feedback in the form of a bug report, you let the automated test case give you that feedback while coding and adding new stuff.
For example:
[TestMethod]
public void ShouldReturnCleanedConnectionStringAndSchemaTranslations()
{
//snip snip snip
Assert.AreEqual(cleanConnString, result);
Assert.AreEqual(1, schemaTranslations.Count(), 'There should be 1 schema translation');
}
When this test fails, do you know what went wrong?? Yes, you have to open the details of the test failure and see which assert failed. But wouldn’t it be better to split them (you see the ‘AND’ in the test name) and create two, like
[TestMethod]
public void ShouldReturnCleanedConnectionString()
{
//snip snip snip
Assert.AreEqual(cleanConnString, result);}
}
[TestMethod]
public void ShouldReturnSchemaTranslations()
{
//snip snip snip
Assert.AreEqual(1, schemaTranslations.Count(), 'There should be 1 schema translation');
}
Now when one of those two tests fails you immediately see which kind of code is probably broken, right?This kind of approach has several advantages. You now even optimized the provided feedback in that – in the best case – you don’t have to even open the details and start to debug in order to understand what broke your test. Moreover when you refactor your code you have to touch less tests. Remember, small tests tend to break less often than large, big fat test methods. And finally, small tests are much easier to understand, fix, adapt etc…
Naming Conventions May Help
Good naming may actually help you identify tests with multiple responsibilities. These worked well for me:
- GivenSomethingIsTrueThenItShouldReturnSomeSpecificResult
- ShouldReturnSomeSpecificResult
Already when formulating the test name you quite quickly see any muliple expectations. What do you think?
Reference: Testing and the Single Responsibility Principle from our NCG partner Juri Strumpflohner at the Juri Strumpflohner’s TechBlog blog.