There you go, those are my 10 rules of (unit) testing. It’s nothing exciting, really. Everyone is so agile these days. Are you agile? I bet you’d say: I was born agile.
Here I come with my own 10 commandments. I came up with those while doing research on mock frameworks (haven’t you heard about Mockito, yet? it’s the ultimate tdd climax with java mocks). I browsed so much of our project’s test code that I feel violated now (codebase is nice, though).
- If a class is difficult to test, refactor the class. Precisely, split the class if it’s too big or if has too many dependencies.
- It’s not only about test code but I need to say that anyway: Best improvements are those that remove code. Be budget-driven. Improve by removing. The only thing better than simple code is no code.
- Having 100% line/branch/statement/whatever coverage is not an excuse to write dodgy, duplicated application code.
- Again, not only about test code: Enjoy, praise and present decent test code to others. Discuss, refactor and show dodgy test code to others.
- Never forget that test code is production code. Test code also loves refactoring.
- Hierarchies are difficult to test. Avoid hierarchies to keep things simple and testable. Reuse-by-composition over reuse-by-inheritance.
- One assert per test method is a bit fanatical. However, be reasonable and keep test methods small and focused around behavior.
- Regardless of what mock framework you use, don’t be afraid of creating hand crafted stubs/mocks. Sometimes it’s just simpler and the output test code is clearer.
- If you have to test private method – you’ve just promoted her to be public method, potentially on different object.
- Budget your tests not only in terms of lines of code but also in terms of execution time. Know how long your test run. Keep it fast.
Number #1 is my personal pet. Everybody is so test-driven but so little really care about #1 in practice. Best classes, frameworks or systems offer painless testing because they’re designed & refactored to be testable. Let the code serve the test and you will produce delightful system.
Number #7 is a funny one (‘Cos we need a little controversy). The whole world rolls in the opposite direction. Maybe I just don’t get it… yet. Or maybe it’s because I paired with young one-assert-per-test guy once. He cunningly kept writing test methods to check if constructor returns not-null value. If I had to play this game and chose my one-something-per-test philosophy I’d steal MarkB’s idea: one-behaviour-per-test. After all, It’s all about behavior…