Tinrate Wiki

How do I write good unit tests?

Good unit tests check one small behaviour at a time, are independent of each other, and are easy to read. Name them clearly, follow an arrange-act-assert structure, and avoid testing implementation details.

Start with the behaviour

A unit test should verify a single behaviour of a small piece of code, such as a function or class method. Decide what the correct result is for a given input before writing the code under test.

Structure each test

Use the arrange-act-assert pattern:

  1. Arrange the inputs and any dependencies.
  2. Act by calling the code under test.
  3. Assert that the outcome matches what you expect.

Keeping these sections distinct makes tests easier to read and debug.

Name tests descriptively

A good name states the condition and the expected result, for example returns zero when the cart is empty. When a test fails, the name should explain what broke.

Keep tests independent

  • Each test should set up its own data.
  • Tests should not depend on execution order.
  • Avoid shared mutable state between tests.

Avoid common mistakes

  • Testing private implementation details, which makes refactoring painful.
  • Writing tests that always pass because they assert nothing meaningful.
  • Mocking so heavily that the test no longer checks real behaviour.
  • Chasing a coverage number instead of covering important logic.

Include edge cases

Test empty inputs, boundary values, and error conditions, not just the typical path.

When to ask an expert

The right level of testing for a system with external services, databases, or regulatory needs can differ a lot. A senior engineer on your team can advise on what to unit test versus cover with integration tests.

Ask an expert in Software Engineering

All Software Engineering experts and questions

How to Write Good Unit Tests