The 9 rules for writing good Unit tests

The 9 rules for writing good Unit tests


In the last months, my team and I have been working a lot on adding and improving our unit tests. But at some point, I realized that the main rules to master in order to write good unit tests were not always followed...

So I thought that a little reminder could be useful. So here are the 7 rules to know for writing good unit tests:

  1. Understand the code being tested - this is fairly obvious, but if you don't understand what you're testing, you can't test it effectively.
  2. Test all possible execution paths and edge cases - generally, each possible execution path in your code deserves a unit test.
  3. Write independent tests that can be run in any order.
  4. Keep tests simple and fast - running the unit tests on your project should take a few seconds at most.
  5. Only test one layer (mock the others) - if you're testing a service like ItineraryBusiness, your ItineraryDataAccess layer (used in your ItineraryBusiness) must be mocked, as you're interested in unit testing the business logic, not the data access.
  6. Give tests meaningful names - this is probably one of the most important rules. After modifying some code, if you see that a test is broken, you should be able to understand what happened just by reading its name. A good example for a typescript method like validateProfile: "it should return false if the profile is missing an email"
  7. It is useless to test pass-through and private methods
  8. Integrate your unit tests into your CI to make sure you never let them rot
  9. Rethink your code if writing tests proves difficult - most of the time, if testing your code is difficult, it means that your architecture as some flaws. Is there a better way to design it?

I'll probably write another post, some day later, with some examples in .Net and Typescript.

If you have any questions, don't hesitate to ask!

Happy coding to all