Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

Write the Minimum Necessary Code In Your Unit Test Case That Makes It Valuable

2 min read

Maintainability is of major importance in software development. Usually writing tests against your codebase increases maintainability in that it gives you some degree of freedom in making changes, at the same time assuring you did not break any existing logic. But, what needs to be kept in mind is that tests need to be maintained as well and that point should not be underestimated. Therefore, paying attention in writing maintainable tests is a very important ingredient for getting the most value out of your automated test suite (and for boosting your development speed).

So, what are the major points of importance to achieve maintainable tests?
Actually there are a bunch of them like
  • structuring tests according to the AAA principle (Arrange, Act, Assert) or
  • testing a single scenario per test case.
Another important point is that you should only write the minimum necessary logic in your test setup that is required for your tests to verify the scenario it should. For instance if you have the following dummy method..
...
public bool DoSomeInterestingStuff(MyStuff theStuff)
{
if(theStuff.IsInteresting == false)
{
throw new ThisIsBoringStuffException();
}

//start doing the really interesting stuff here
}
..and you'd like to verify that it throws an exception if the IsInteresting is not set to true, then you should only set that variable in your test setup, like
[TestMethod]
public void TestDoSomeInterestingStuff_StuffIsNotInteresting_ShouldThrowException()
{
//Arrange
MyStuff someBoringStuff = new MyStuff
{
IsInteresting = false;
};

//Act
...
}
The test setup should just contain the setting of the IsInteresting flag although MyStuff might have other properties as well. This assures that your test remains readable and clean. Someone else will immediately perceive the main intention of your test and moreover it remains maintainable as you don't have to modify your test setup in case you remove or add other properties to MyStuff.
Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus