Unit Testing is very valuable, but I would be lying if I said it's easy. It takes effort to get good unit test written.
A Unit Test is written on a Unit of code (yes, duh!) But, what's a unit of code?
A unit of code is smallest piece of code that does useful work.
Getters and setters usually are smallest piece of code, but often don't do much useful work (languages like
Ruby and Groovy generate them for you automatically, but that is for another blog). So, I would not
care to get them unit tested separately (they may get called in other tests, and that's OK).
What about a method that has a long running task or that has to wait for an event that may happen at any time?
Sure it's doing useful work, but it may not be "small." Chances are you can break it into smaller methods,
where the method then may wait for an event, but when the event is received, can then call another (small)
method that does useful work. In this case, I am quite happy unit testing this small method that does the useful
work first and not worry about the event part yet.
Don't we need to unit test the event receiving? We would separate the part that's waiting for the event into may be
another small method, put in a mock for the event source if needed and have the event receipt unit tested. But,
I would take that as the second or third test, not the first.
When writing unit testing, some times we want to start testing everything we can think of. Sure, we are eager to have
the functionality tested, in its entirety. But, that leads to two problems. We will find it very hard to comprehend
the testing. We may write a large test. We may also overly complicating the solution in the process.
Keep it small, keep it focused, fast, and automated. That is easier to say, but on a real project, can it get hard?
Yes it does. When that happens, take a short break. Stepping away from the code helps us think. Ask for help?find a
colleague and bounce some ideas. While you are trying to explain the problem, you go though logical steps in your mind
and this often helps you to figure out an approach.
And once you think you've figured it out, ask your coworker to do a quick code review, not just the code, but the test
also. You only stand to improve you code this way. Any who does not want to improve? :)