Unit-testing – Is it normal to spend as much, if not more, time writing tests than actual code

testingunit testing

I find tests a lot trickier and harder to write than the actual code they are testing. It's not unusual for me to spend more time writing the test than the code it is testing.

Is that normal or am I doing something wrong?

The questions “Is unit testing or test-driven development worthwhile?”, “We are spending more time implementing functional test than implementing the system itself, is this normal?” and their answers are more about whether testing is worth it (as in "should we skip writing tests altogether?"). While I'm convinced tests are important, I'm wondering if my spending more time on tests than actual code is normal or if it's only me.

Judging by the number of views, answers and upvotes my question received, I can only assume its a legitimate concern that isn't addressed in any other question on the website.

Best Answer

I remember from a software engineering course, that one spends ~10% of development time writing new code, and the other 90% is debugging, testing, and documentation.

Since unit-tests capture the debugging, and testing effort into (potentially automate-able) code, it would make sense that more effort goes into them; the actual time taken shouldn't be much more than the debugging and testing one would do without writing the tests.

Finally tests should also double as documentation! One should write unit-tests in the way the code is intended to be used; i.e. the tests (and usage) should be simple, put the complicated stuff in the implementation.

If your tests are hard to write then, the code they test is probably hard to use!