Insights & Advice

How unit testing code changed my life.

Writing unit tests is an absolute must for any modern application. This is especially important with greenfield projects for startups that we often work on. 

Unit testing seemed like a lot of extra time and work for not much gain when I was first introduced to the concept. However, as the applications I worked on grew, I began to realise their true value.

Photo by Markus Spiske

What is unit testing?

Unit testing is a method of testing a specific module of an application to ensure it produces the desired result. For example, let’s pretend there’s a part of your code base that is used to register users. You expect that the user will be inserted into the database and a welcome email sent. Unit tests would simply check that the user was correctly inserted into the database and that an event was fired to send the email off. 

Here’s what unit testing can do for you.

  1. Prevent unexpected errors in the future
  2. Although we often strive for decoupled code, there are always going to be instances where this is not possible or appropriate. By unit testing your code you can ensure that a new feature or a refactor hasn’t negatively impacted the functionality of your code. 

    Have all your unit tests run before code is deployed to the server – whether this be automated using a CI/CD pipeline or manually by the project lead. Assuming your tests have good coverage and if they all pass, it is safe to assume the new feature hasn’t broken any functionality.

  3. You will write higher quality code
  4. When writing unit tests using the TDD workflow (see my other article) it’s very easy to highlight and eliminate any edge cases that may arise. If you dive straight into the code, you may be so focussed on writing something that works, that you miss an important security flaw or edge case. I often find that most of my unit tests are checking things the code shouldn’t do rather than what it should do. 

  5. It forces you to think about your code structure
  6. A less obvious, but no less important, benefit is it encourages you to write decoupled code. To be able to write a good unit test you need to be able to control the input of the code you are testing. By writing code that is hard to unit test you are likely to be writing code that will be harder to maintain in the future. It’s not always the case, but it’s good to consider the testability of the code you are writing. 9 times out of 10 if your code is easy to test then it will make the entire maintenance process much more enjoyable for all involved. 

Get unit testing!

I’m yet to hear an argument as to why someone wouldn’t unit test their code. Even with a rapid moving startup, unit tests are an absolute must to ensure code is high quality, maintainable and that no unexpected bugs are introduced.

This website uses cookies to improve your experience. By using Prism, you accept our use of cookies.