If you are new to writing unit tests, here is a list of common beginner’s mistakes. As Warren Buffet famously said “It’s good to learn from your mistakes. It’s better to learn from other people’s mistakes”.
- Testing multiple things at the same time
New developers tend to try and test big chunks of code out from top to bottom. Often these kinds of code make it hard to test single behavior. The more appropriate way to go is to refactor the code and split test cases and code into more manageable units so that you should be able to test one thing at a time. - Relying too much on external services
More often than not, the code we write depends on external services. Generally your code will interact with such services and your unit code should not rely on them because the state of those 3rd party services is not your responsibility. In another words, your tests should guarantee functionality of your code not the consistency of these services. - Aiming for coverage
Coverage is just one metric for your tests and this cannot be your sole aim. You should use this metric not to measure what has been covered but to understand what has been left out, and if it needs to be tested as well. - Using bad test names
If the test name is bad, confusing or even outright illogical, then reader will need to read the actual test code implementation. Therefore, having understandable test names can save a lot of time. - Forgetting the essence of readability
The code we write is more read than written. That is why it is essential to produce code which readers can understand. In order to achieve this goal, we need to separate the data creation, actions and assertions in the test. There is pattern for this and is called AAA, Arrange, Act and Assert. Basically, the Arrange section is where you set up an object which needs to be tested, the Act section is where you execute the test, and the Assert section allows you to make claims about the outcome.