Writing good unit tests is a challenging tasks. There are so many articles available, that try to explain you how to apply good practices and avoid bad ones, that you could spend at least one year of full-time work reading through all of those articles. And after that, you wouldn’t be any wiser, because you still had to apply the 1.000 lessons learned to your daily coding routine.
So, here’s the deal: in this article, I will give you 3 pragmatic rules. Consistently apply these rules in your projects, and you will have the perfectly understandeable and maintainable unit test code.
1. Consistent Naming Strategy
A consistent naming strategy helps you in (i) navigating your testing project to find particular unit tests, and (ii) adding test cases at the right position of your project, to easily find them at a later point in time. Both aspects make maintenance much easier.
More specifically, your naming strategy defines rules on how to name (i) folders of your testing project, (ii) test classes, and especially (iii) test methods.
Based on these three aspects, the context of a unit test should be cristal clear. Deriving this context correctly not only helps in maintaining test cases, but also understanding what a test case actually does.
2. Apply the AAA Pattern
What is the AAA Pattern? Basically an efficient and pragmatic way to structure your unit test code. It is easy to use, but yields awesome results when it comes to understanding, and especially maintaining, your test code.
AAA stands for Arrange – Act – Assert. And this is also what you do when applying the pattern.
- You define an Arrange block in your tests, in which you prepare the test execution (setup system under test, instantiate objects for test input/expected output, setup mocks, …).
- After the Arrange block, you define an Act block, that executes the system under test and collect the execution result.
- After the Act block, you define an Assert block, that checks the actual against the expected result (using assert statements).
3. Have someone else explain your code to you
This is the ultimate check of understandability. If someone else doesn’t understand what’s going on in your unit test (or he/she doesn’t bother knowing, because it would take way too much effort to decrypt from your code), chances are pretty high that in a few months, you won’t, either. This is the ultimate killer of teamwork, reusability, maintainability, documentation, you name it…
So take this pragmatic test and see whether what you’ve produced can be understood by someone else – and learn from problems that others are having with your code! This is how you learn to produce perfect unit test code!
As guidelines, you can take some aspects from
this checklist. But in general, it’s really just about understanding what your test is doing, and how he’s doing it.
Try out these three quick fixes in your next project and let me know about your experiences, in the comments section below!
Daniel Lehner