Unit testing is like wearing a seat belt

This is not a tutorial on HOW to write unit tests. These are random thoughts on WHY to write unit tests (and wear seat belts).

Seat belts won’t stop me from getting into an accident

Anthony: No, you are right. You can still get into plenty of accidents while wearing a seat belt. But buckling up can save your life if you do get into an accident.

Unit tests will NOT prevent all bugs from entering your code. Writing unit tests will not be as drastic as saving your life. But writing unit tests can protect you from regressions and known edge cases.

You can still get hurt when writing tests, but (hopefully) it will hurt less.

I got into an accident and wasn’t wearing a seat belt…and I’m fine

Anthony: No, you are right. There are stories about people who suffered horrible injuries while wearing seat belts. I’m sure there are stories of people uninjured without seat belts.

You can write buggy code with tests.

You can write perfect code without tests.

I’m sure I write perfect code 99% of the time (**nose grows**), but I’ll keep writing tests for that 1%.

It’s hard to measure how effective tests are. But there is almost no risk in writing them, and very high reward. So be safe and wear your seat belt.

Don’t be such a cub scout and tell me to buckle up.

Anthony: Some people are headstrong about never wearing seat belts. Some people are headstrong about never washing their hands after flushing. ¯\_(ツ)_/¯

After disasters, some people will realize how tests could’ve helped them. They start singing the praises of writing unit tests.

But others will continue to look at you with disdain during a code review when you ask them where the unit tests are. There’s nothing you can do here.

I’m just going on a short drive. What could happen?

Anthony: Agreed, wearing a seat belt might seem unnecessary when going on a 2 minute drive to your friend.

Are you working on a throw-away project? Or working in a start-up that doesn’t have a chance of launching? Then forget tests!

Anthony: But…a drive to your friend could be familiar to you, but a dangerous trek for a student-driver. I’d tell them to wear the seat belt.

Working on code in a team with junior developers? Unit tests can be more valuable than a README.md.

Anthony: What if your short drive turns into a long road trip? I’d wear the seat belt before getting on the highway.

What happens if your throw-away project doesn’t actually get thrown away? We should start thinking about writing unit tests and paying off technical debt.

Conclusion: Should we wear seat belts?

Some people think wearing seat belts are a waste of time. But do it enough and it becomes habit. Keep writing tests until it becomes second nature…just in case your code isn’t perfect.