practiceEngineering & architecture

Unit Testing

Unit testing checks a small, defined piece of software quickly so developers can detect behavior changes close to their cause.

Download Markdown (.md)

01What it means

Unit testing exercises the behavior of a small part of a program, such as a calculation or a closely related set of objects. The team defines the unit boundary. Dependencies may be real or replaced with test doubles when isolation improves speed and control; testing every private function separately is not a requirement.[1][2]

02Why it matters

Fast feedback helps developers locate failures while a change is still small. Tests also preserve important business rules during refactoring and provide executable examples of edge cases that prose requirements can overlook.

03When to use it

Use unit tests for deterministic rules, transformations, and boundary conditions. Use integration tests for real database or service interactions and broader checks for complete journeys. Unit testing can be used with or without the test-first sequence of test-driven development.

04How it works

  1. Choose a meaningful behavior and define its inputs and observable result.
  2. Arrange a small, explicit fixture with controlled time or randomness where needed.
  3. Exercise the behavior through a stable interface.
  4. Assert the intended result, including relevant boundary and failure cases.
  5. Run frequently and revise tests when agreed behavior changes, preserving readability.

05A practical example

Example

A booking team tests a cancellation-fee calculator immediately before, at, and after its deadline. A date-handling refactor changes the boundary result, and the test identifies the rule that needs review before the change reaches checkout.

06Where it breaks

A unit test only checks the cases and expectations encoded in it. Excessive mocking can validate an imagined system, while tests tied to internal structure make harmless refactoring expensive. Fast passing tests cannot establish that deployed components work together.

Common mistakes

  • Asserting implementation details instead of meaningful behavior.
  • Treating a high coverage percentage as proof of correctness.
  • Sharing mutable fixtures that make results depend on test order.

07Sources

  1. Unit TestMartin Fowler · Practitioner guidanceUnit Test
  2. Best practices for writing unit testsMicrosoft · Official documentationBest practices for writing unit tests
View saved topics

Start typing to search titles, definitions, categories, and frameworks.