"I've always avoided it because it seems like so much extra work" - Tommy Williams
Once you learn about unit testing, and how it works, the natural question is: Is it worth it? When you learn about the other types of testing, specifically End-to-End, which REALLY makes sure that your application works, then why bother with unit testing? As my friend Tommy above so eloquently put it…it just seems like so much extra work.
Well, I think we can quickly go over some really good information about why unit testing truly is a good idea.
I'm going to focus on two of the very many benefits of unit testing.
First: Finding Hidden Deficiencies
In order to understand this benefit, I'll use an analogy. Let's say you are building a car, and you want to test that the car is working properly. An End-to-End test is basically taking that car out for a drive and seeing if it works properly. That seems like that's all you need right? If the car is good, then you're good yes?
Well, let me tell you a short story about the two cars I bought last year. Both of them had hidden cracks in the header, which showed up only after a while. They were devastating flaws that basically made the cars worthless.
Now let's look at how a unit test could have helped. If I had been able to extract just that one part and look at how it was operating in isolation, I could have found the deficiency. Any experienced developer will tell you that a working system still definitely has bugs. Hidden away, just waiting to come out at an inopportune time.
Second: Improved Architecture
In order to do unit tests, you have to be able to extract a single unit, and "exercise" it in isolation. This requires that the unit is easily isolated from its dependencies and collaborators. If you can do this, then your unit follows several best practices for good design and architecture. Simple.
But wait, you say what if I just write my code that way anyway? Then I don't need unit tests. Well, recognize that in this case, the unit tests are actually a test of good architecture. They don't rely on you THINKING that you have followed these principles of good architecture. They only work if you really HAVE followed these principles.
That way it's a check on your implementation of these principles.
These are just two of the many reasons to write unit tests for your code, but they are in my opinion two very compelling reasons.