Often I get asked: Why should I write a test. What should I answer?
My preferred answer is: It’s an insurance to you.
At the time you have tests for your code, somebody else can do modifications on your code and you are sure it still does what it should. Otherwise your test will fail. (Well some people think: Why should somebody else modify my code? That’s impossible, this code is too complex, as it can be modified by somebody else… But this is another story.)
I also like the counterquestion: How can you assure me this code is working?
What I get to hear is: Hmm… I have tested this code. What crosses my mind is: “Yes, works on his machine, at the moment… Very good, he loves his code. And later? One of the customers has the good idea to use a long time implemented feature. (Yes, now it’s a bug) This happens if the libraries (or the framework) you base was changing. Some feature has changed and you never took notice. But a year ago, it was working…”
In my opinion everybody is writing tests for himself. It helps you to check the code is doing what you think it should. If you write a test while you are programming, you wont need much more time. If you’re used to TDD you’ll even need less time to implement some feature. Additionaly you have a guarantee that even a year later your feature still works. And finally the time you save if you have to bug fix the code later in case of change libraries etc. is enormous.
From a TDD (Test Driven Development) perspective unit tests help you also
– find a design that matches your requirements and is as simple as possible. Fast feedback for design decisions.
– work in parallel (when using mocks, fakes, stubs)