Testing and the Single Responsibility Principle
3 min read
3 min read
Automated testing is hard! Therefore, if you're about to learn it, just keep going. Resist the initial learning curve as afterwards it'll allow you to adopt a completely different programming style. A common problem I've observed is that (mainly) "testing newbies" tend to create huge, bloated tests cases which quickly start to get unmanageable. Usually this discourages them and they abandon their tests. So what's the key?
When you start with automated (unit) testing, you usually apply a test-after approach. That's natural. While I think you should jump into testing in a test-first manner immediately, you will naturally end up doing test-after and then eventually slowly move back to real test-first. This test-after approach however is what lets you create big huge test cases normally as it is extremely difficult to focus on the single test cases.[TestMethod]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
public void ShouldReturnCleanedConnectionStringAndSchemaTranslations()
{
//snip snip snip
Assert.AreEqual(cleanConnString, result);
Assert.AreEqual(1, schemaTranslations.Count(), "There should be 1 schema translation");
}
[TestMethod]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...
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");
}