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.
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.
- Prevent unexpected errors in the future
- You will write higher quality code
- It forces you to think about your code structure
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.
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.
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.