Unit Testing is an essential activity in every software project.
Why? Without Unit Tests, you never know when you break some parts of your software. Every change in the source code might potentially break your whole system – and chances are high that you won’t even notice (but your users will, for sure).
But on the other side, writing unit tests is also one of the most boring tasks in software development.
- You have to think about what you want to test, how to test it, and then write code for it
- If you want to understand your code in a few months (or others should understand and work with your unit tests), you also have to stick to patterns and clean code conventions in order to
- And if you’ve finally written your perfect unit test code, chances are high that is will have to constantly adapt it, as soon as you perform changes in your tested code. Which means reworking and maintaining.
In all of the tasks mentioned above, there’s no innovation happening. You don’t write new functionality, you just check whether the functionality you’ve already written works or not.
So basically, writing unit tests is just boring. And it costs a lot of time.
That’s why I personally use the following approach when it comes to Unit Testing:
Define what you want to test, and let the rest be generated automatically.
Why?
It saves me about 70 % of my time when it comes to unit testing. Time that I can use to actually create new functionality, instead of writing and maintaining test code. But let’s be a bit more specific. What are the benefits of auto-generated test code for every developer:
- Automatically stick to patterns, best practices and clean code conventions. You don’t have to think about making your test code clean and readable, ever again. Simply define rules how your generated code should look like (if you use professional tools, these rules are usually implemented for you already). Code generation tools make sure that these rules are satisfied by your generated test cases.
- (The obvious one) Write less code. Code-Generation allows you to define what you want on an abstract level. Repetitive syntax that usually has to be written for each test case can therefore be handled by the generation tool. In its essence, this allows you to write less code, and focus on defining what you actually need.
- Easy overview. Visual presentation techniques of modern test generation tools allow you to easily gain and keep an overview of your existing test cases. This makes test case management simple and effective.
You can write your own code generation tool as a side project (some helpful technologies are
the Roslyn, the Eclipse Modelling Framework, or the MPS DSL tool), or just use existing tools that generate test code for you (just google “test code generator” and you will find a list of appropriate tools).Try it out and let me know about your experiences, in the comments section below!
Daniel Lehner