Refactoring unit tests for readability
Any fool can write code that a computer can understand. Good programmers write code that humans can understand. - Martin Fowler, 2008
The code you produce will be read. The “brillant” class you have just written and forgotten might sit idle for many months. Then it breaks. It’s Friday evening and hotfix is needed right now because crucial invoicing procedure is generating weird, negative invoices for no reason!
Your poor colleague, Joe, is assigned to this dreaded task only to find your class. With elaborate algorithms solving simple tasks, because optimization1. With rarely used LINQ method. With neat, little code trick. With bit of “hackerish” list operations you had then learnt from some cool blog.
Sure, the implementation worked great. Unfortunately, not for Joe. He most likely understands nothing of it. Not because he has brain freeze or is slightly slower. It is because you had produced unreadable, unmaintainable ball of mud.
Why readability matters
Joe would have been just fine if you had kept your solution simple. Saved cool tricks and hacks for your pet projects at home. Didn’t optimize prematurely. Instead, focused on solving problem at hand and making sure your code is as simple to follow as possible. It is invaluable in situations like the one described above.
Now… how do you improve readability of your code? To discover that, we’ll take a look at the ExportTaskScheduler class, solving one specific business requirement – scheduling export:
That’s all there is. This code is fairly simple and readable. Method has well-defined, single responsibility (schedules export2) and is only few lines long. Anybody reading it should be able to tell what’s going on almost immediately. Readability goal has been achieved. Or… has it?
Let’s take a look at its unit test:
This code is certainly not as readable as implementation one. Why is that so? Unfortunately, unit tests are often treated as “second class citizen”, a code where regular practices and patterns don’t apply. This is a mistake. You will often find test methods without descriptive name, spanning multiple screen, weird mocks usage, cryptic variables naming – all developer’s careless attitude visible through code. Just as if unit test was some sort of different, less important code. It is not. It is production-level one, just as any other.
Without further due, let’s go over the issues one by one.
1. Test method name
TestScheduleFutureExportTask tells us nothing. This is bad because method name is first thing we will see (especially when test fails) and it’s the name which should give us brief overview of testing scenario (so that we get to know what we are dealing with quickly). Using one of the popular naming conventions we arrive at something closer to
2. Variables names
Since we deal with two schedulers, high level one (scheduling business process) – ExportTaskScheduler, and low level one (scheduling code commands described by some objects) – FutureTaskScheduler, we should pay extra attention to how these two variables are named. The current choice (
scheduler) is rather poor as it is harder to discover which is which. Rule of thumb is to keep the variables names long, without any “smart” abbreviations. In the long run,
exportTaskScheduler is an immediate tell, while
exTskSchd are not.
3. Dealing with time
We use FluentAssertions syntax to neatly create DateTime instances but truth to be told, the exact value is irrelevant in this test. We need some point in time because we assert how other values relate to this given point (task is scheduled 10 minutes from now). We are better of with hiding exact value, for example in static field:
Then, our asserts are much more verbose:
4. Asserting values
Since this is the rare test of verifying whether some other component was called (with correct parameters) and we are already doing asserts inside
WhenArgumentsMatch the simplicity has taken a hit. What we could do is extract the assertions to separate methods. Our test now looks like this:
It is good as it is but there are few more things we could do. They might not be as beneficial in this simple case but as the number of test cases grows, they will make a difference.
5. Extracting instances creation
For any test case, the way system/class under test instance is created is most likely irrelevant. What matters is easy access to such instance and clear, intuitive name (and we’ve already dealt with that). To put that noise away, we can move such preparation steps elsewhere. For example, to NUnit’s SetUp method where each instance is created and stored in class field:
This way, the arrange part tells that current time is this and this, which is the only relevant information.
6. Verbose arrange
…which could be improved further. How? By wrapping it in a more verbose method, like:
The more test cases we got, the more beneficial such verbose arranges get. Similar thing can be done to assert part but since it will be different for different tests, there is little gain (we won’t be able to reuse such verbose assert). The final version of unit test might look like this:
Readability is important. Simple, easy to understand code is important. Somebody is going to read our work one day, maybe in a big hurry. We don’t want to make their work harder.
To learn more about practices similar to the ones presented in this post, I recommend Robert C. Martin book, Clean Code, and his training videos based on the book (these can be found online).