We’ve already established what a unit test is in one of our previous articles. Now it’s time to define when you should write a unit test! A question that is not that easy to answer.
3 approaches of when to write a unit test
- If you are an early bird then you probably prefer the Test Driven Development (TDD) approach. You start by writing unit tests first and then write the actual code later.
One of the biggest advantages of Test Driven Development is that you actually get better quality code since you already take all possible mistakes into account before you implement anything. - However, the most common approach although is to write unit tests during the implementation process. Here you try to develop awesome code while always having the actual testing process in mind. This approach is definitely something for more experienced developers.
- Additionally as a developer you are sometimes confronted with the task to maintain legacy code. Legacy code describes code that is no longer supported. Writing unit tests for legacy code is very difficult and cumbersome.
Best practices of unit testing
As we have previously learned creating unit tests is a crucial process in producing quality code. You should either write unit tests early on during the implementation or you should go for the Test Driven Development approach.