How to write good tests

Forketyfork
3 min readFeb 4, 2022
Image by Nandhu Kumar from Pixabay

A secret to writing good tests is keeping in mind that there are only two reasons for a test to exist:

1. Making sure your code works as expected.

2. Avoiding regression bugs.

That’s it. There are no other reasons for a test to exist. Think of it whenever you face any of those questions:

  • should I try to achieve 100% code coverage?
  • should I write a test for this specific functionality or not?
  • should I mock some specific dependency or not?
  • what do I need to assert and what not?

Reason 1. Making sure your code works as expected

A good test helps to ensure that your code works as expected if it’s not obvious from your code. Do not write tests for something which is obvious from the code.

We all know how code may get complicated, may contain lots of non-trivial conditions or sequences of steps depending on one another. Sometimes you may have confidence that it works properly, but it may not be obvious for someone who reviews or updates your code.

It’s perfectly fine to write a test for such code.

But if this is not the case, if the code you try to test is trivial, then check if this test fits…

--

--

Forketyfork

Software developer @ JetBrains CodeCanvas. I write technical how-to articles and occasional rants on software development in general. Opinions are my own.