Wednesday, July 4, 2007

"Just one test!"

I have read in a couple of places now (amongst other generalities) that a unit test per method is the standard "rule of thumb". I have been surprised at this. I understand that at least one test per real method (not one line getter/setters) is a minimum but to generalise it to only one is a bit odd.
This was kinda sparked off by this post http://blog.sidu.in/2007/06/pre-run-tasks-unit-testing-anti-pattern.html. I am not coming down on the poster at all and I may have over reacted to an aspect of the post that was certainly not the main point of the thread.
But just one test per method? It got me thinking.
I generally have a test to cover each of the paths in the method (to an extent).
I never really thought about it but I guess complete coverage* would come from tests that match each of the paths and therefore the cyclomatic complexity of that method. If you have an increasing number of tests for a method you may want to reconsider the functionality of the method. Can it be refactored?
This I believe is another benefit of TDD. It forces you to think about function design first not just start the torrent of code and hope that what comes out works. This is also a reason to write the tests first. I find it amusing that some still write the test after they write the code. I mean really, why not define what you want then build it.

* no im not a coverage nazi :p

No comments: