How do you write good tests?

One aspect of Clean Code is that code is testable and tested.

Sonar enables users to import test coverage reports – which show how much of a codebase has been touched by test code. And, good Code Coverage doesn’t necessarily mean you have good tests.

Sonar offers some rules for writing good tests for Java, JavaScript, TypeScript, Python, PHP, and C#!

We want to ask you – how do you ensure that your tests don’t just touch your product code, but are testing things in the right way? What practices do you (and your team) encourage when writing tests? What gets in the way sometimes?

I use test-driven development (TDD):

  1. I write the test code before finishing the main code logic.
  2. I ensure the test is able to fail.
  3. I finish the main code logic.
  4. Now, the test passes, but if one day the main code logic changes, I’m confident the test will be able to fail.
  5. I run all the tests related to my new main code logic to check its coverage.
  6. I add the missing tests to complete the coverage, but I start with some wrong exprected results in the tests to make the tests fail.
  7. Then, I provide the right expected results to make the tests pass.
6 Likes