Web apps & software

What is unit testing?

Unit testing means writing small automated checks that run one function or class in isolation and confirm it returns the expected result, so mistakes are caught within seconds of being made.

What one looks like

A fare calculator has a function that adds a night surcharge. A unit test calls it with a 23:30 pickup and asserts the surcharge appears, then calls it with 14:00 and asserts it does not. Edge cases such as exactly midnight deserve their own tests.

Qualities of a good one

  • It runs in milliseconds with no network, database or clock dependence.
  • It fails for one clear reason and its name says what broke.
  • It tests behavior, not internal details, so refactoring does not break it needlessly.

Limits

Passing unit tests do not prove that the parts work together, that the database query is right or that the screen looks correct. They sit at the base of a testing pyramid, with fewer integration and end-to-end tests above them.

Tools

Jest and Vitest for JavaScript, PHPUnit, pytest, JUnit, xUnit and XCTest are common choices. Dependency injection makes code easier to test.

Questions, answered

Enough to cover the business rules that would cost money if wrong. Chasing 100 percent coverage often produces weak tests.

The developer who writes the code, ideally in the same change.

By the Stegnor team · Updated