Now, I've preached the unit testing gospel in theory for a while now, but experiencing it in practice is a different matter entirely. Boo has automated tests, but they're really mostly integration tests and I always wrote them after finishing everything else. But today, in an underground coding session, I --
- Wrote some code. It looked OK, but I really wasn't sure about it.
- Wrote a test for some method. It came out red.
- Fixed the bug.
- Wrote two more tests, called SomeMethodTest2 and SomeMethodTest3.
- Fixed another bug, and realized SomeMethod isn't very well written.
- Rewrote SomeMethod. Ran all 3 tests. Fixed bug in new implementation. Ran tests. All green.
- Wrote some other methods and their tests.
- Felt uneasy about three of my tests being duplicates of three of three other tests, but for another method. Realized I'm actually testing the same thing being done in the two methods.
- Extracted that same thing out to its own method and only tested that. The tests for the original two methods got trivial since I was already confident about the hard part; so now I was only testing that they were correctly using that part.
- Reflected that understanding by switching from calling my tests SomeMethodTest to DoingThisShouldCauseThat. Dropped some unneeded assertions and moved others to where they belong.
- Finished the class with some more methods and tests. All green.
- Ran code coverage on it, just for fun. One if statement had the wrong color.
- Realized I'm missing another fundamental test. Wrote it. Green and covered.
- Rewrote SomeMethod again to be even simpler, guessing about whether I should round something up or down. 3 reds.
- Changed code to round the other way. All green. Guess that answers my question.
- Reran all 15 tests. All green, all the important bits covered. Checked in.
- Emailed the others about the new code and where it can be found. Went home feeling content.
It's like, all those people - they weren't lying, you know? It really does work that way. Unit tests don't just reveal bugs and save time on refactoring; they also point out pain points in the design and can help you (and others) understand what the code should be doing. Another bonus is that they make you feel good about your code while writing it, and to me, that's really worth the effort.
I'm no longer a unit tests virgin, and goddamnit, it feels so sweet (and doesn't hurt as much as your mama said it would).