I’ve recently been tasked with testing some COM objects of the desktop app I work on. What this means in practice is writing a large number (>100) unit tests to test different but related methods and objects. While the unit tests themselves are fairly straight forward (usually one or two Assert()-type checks per test), I’m struggling to figure out the best way to write these tests in a coherent, organized manner. What I have found is that copy and Paste coding should be avoided. It creates more problems than it’s worth, and it’s even worse than copy-and-paste code in production code because test code has to be more frequently updated and modified.
I’m leaning toward trying an OO-approach using but again, the sheer number makes even this approach daunting from an organizational standpoint due to concern with maintenance. It also doesn’t help that the tests are currently written in C++, which adds some complexity with memory management issues.
Any thoughts or suggestions?
5
Any thoughts or suggestions?
Focus on one test at a time. Be consistent from one test to the next. Reevaluate your approach once you have ~10 tests under your belt.
Realistically, 100 unit tests at ~6-10 lines of code a piece is like a week’s worth of work. Annoying, tedious work… but not a lot of it. Put your head down and don’t over-think things.
2
I’d like to offer the opposite opinion from Anton.
Unit tests are code. The fact that they are not shipped to the customer detracts in no way from their importance to your code base. They are an investment of your programming time that repays itself in the improved speed and accuracy of further modifications of the code base; therefore they merit any good design principle that would apply to your business code.
You give some hints about how duplication in the individual tests could be avoided; I say go for it. The improved understandability of a large test suite more than makes up for the effort of deduplication. Complexity of code, cyclomatic or otherwise, is of course a pressure that you should avoid as far as it’s reasonable, but never let fear of abstraction prevent you from writing your tests as professionally as your application logic.
2
Don’t forget that Cyclomatic Complexity of your tests must be the lowest (about 2). That will help you to avoid making bugs in unit-test. Tests must be as easy as you can do. So, don’t try to make the best design and use all design patterns you know.
Extract all setup code to “helper” classes. This will help avoid copy/paste situations (I see devs copy/paste setup code for the test a lot).