Unit Test

Key points

  • A unit test verifies that the smallest unit of a program (a function or method, for example) works according to spec.
  • It's typically run by developers themselves, while writing code or right after writing it.
  • Because it catches defects at the earliest possible stage of development, it keeps fix costs low.

What a unit test is

A unit test targets the smallest components (modules) that make up a system — "functions" or "methods" — and confirms whether each one behaves as expected. Its defining feature is that it focuses on individual parts rather than the system as a whole.

🔑 Everyday exampleIt's similar to checking that a car's engine works and that its brakes work, individually, before the car is assembled. Confirming that each part works correctly on its own reduces the chance of trouble later, once everything is put together.

What gets verified

A unit test confirms, for a given function or method, whether passing in an input (arguments) produces the expected output (return value).

Pass in
input values
Run the
function/method
Check the
expected output

This confirmation is done not only for normal inputs, but also for unexpected inputs and edge-case values.

How to think about test cases

Unit test cases are mainly prepared from these three perspectives.

Normal casesDoes expected input return the correct result?
Boundary valuesDoes it work correctly right at the upper and lower limits?
Abnormal casesIs invalid input handled with appropriate error handling?

Combining these perspectives makes it easier to prevent bugs caused by unexpected inputs before they happen.

Automation and test code

Unit tests are typically written as test code and run automatically with tooling. Representative tools include Jest for JavaScript, JUnit for Java, and pytest for Python.

Once you've written the test code, you can rerun the same checks as many times as you like, every time the program changes. Compared to manual checking, this also has the advantage of being less prone to missed checks or human error.

Benefits and limits of unit testing

Unit tests have significant benefits, but there are things they can't confirm on their own.

BenefitCatches defects at the earliest stage and smallest scope
LimitCan't confirm how parts behave once combined together

Whether parts work well together is confirmed in the next phase: "integration test."

Summary

A unit test verifies that the smallest unit of a program works according to spec, and it's typically run by developers themselves at an early stage. Preparing test cases from the normal, abnormal, and boundary-value perspectives, and automating them, lets you secure quality efficiently.

Related topics:

🏠 Back to top