New developers will sometimes complain about how Unit Testing requires a lot of time. How much it slows them down, and how they cannot see any good in writing tests for their code.
There are many scenarios which prove that unit testing is necessary. These include speed of development, ability to refactor easily, test-driven development, testing without the need of web container, testing with mock objects etc.
My favorite though is the “client calls to report something weird” scenario. I’ve seen it many times and it goes something like this:
- Your webapp is deployed, weeks ago, and you’ve moved on with a new, exciting project. Everything is feels good, as you’ve completely forgotten about sins of the past (not writing tests)
- Client calls you to report “something weird”.
- You stop whatever you are doing at that moment to switch to that project.
- You connect (VPN or whatever) to the remote server to see possibly logged exceptions.
- You collect your data.
- You try to reproduce the error locally, on the development server.
- You find the bug.
- You issue the bug in the bug tracking system.
- You fix the bug.
- You build for deployment.
- You deploy (while solving any possible application version issues).
- You contact the client.
- Wait for his confirmation that the bug has been corrected.
- You deliver the bug in the issue tracking system.
- Finally you commit the code back to SVN.
…or in whatever order feels more natural to you.
If the above scenario feels OK, and you need some hints on why you should try to minimize such cases, have a look at the costs involved:
- All of these actions need time. Your time.
- Most of them require a context switch. Not only you lose X minutes from your previous work, but also need Y minutes to get back into the flow (mind state) you had previously.
- Some of these steps might not be what you really want to be doing (talking directly to the client).
- You become a slow worker producing bad code.
- People will never trust you with that mission critical application, because your code has a tendency to develop “random features” on runtime (usually involving exciting names such as NullPointerException).
This scenario can definitely happen for tested code. Bugs will always creep into your code no matter what. The point is try to at least minimize the stupid ones. Cases which can easily be covered by unit tests.
Unit testing is important (if not mandatory). If you feel that it needs time, you have to press yourself and do it. It’s a matter of weeks until you become test infected and experience how your software becomes better in less time.
Hints for NetBeans users:
- Got a class that you want to create a JUnit test for? CTRL+SHIFT+U
- Got a class and want to jump to the unit test (and vice versa)? ALT+SHIFT+E
- Want to test the project? ALT+F6