Skip to content
Commitwise
Menu

What makes a unit test good?

LanguagesJunior

In shortIt checks one behavior through the public API, uses an expected value derived from the requirement, runs fast and deterministically with fakes for the network, clock and storage, and would actually fail if the code were wrong.

Model answer

A good unit test:

  • Checks one behavior and is named after it, so a failure says what broke.
  • Arranges input, acts once, asserts against an expected value worked out from the requirement, never recomputed with the code’s own formula.
  • Covers the cases that find bugs: a normal case, boundaries on both sides (7 and 8 characters for an 8-character minimum), empty and invalid input, and error paths. Parameterized tests make that cheap.
  • Is isolated and deterministic: slow or random dependencies (network, database, clock, randomness) are replaced with fakes passed in through the constructor, and no state is shared between tests, so it passes alone, together, in any order and at any time.
  • Can fail: break the code once and watch it go red. Async tests must await their work, or they pass no matter what.

It tests behavior through the public API rather than private methods, so refactoring doesn’t break it.

What they're looking for

Arrange-act-assert, choosing cases (boundaries, errors), isolation with test doubles and injected dependencies, and the idea that a test must be able to fail.

Common mistakes

  • Equating coverage with quality.
  • Testing private methods or implementation details.
  • Ignoring flaky tests or "fixing" them with retries.

More languages questions

Esc

Type to search the whole site.