Skip to content

Unit test

Also called: unit testing, unit tests

Published:

What sets unit tests apart?

Martin Fowler identifies three common traits. Unit tests are low-level and focus on a small part of the system, programmers write them with their usual tools plus a unit testing framework, and they are expected to run significantly faster than other kinds of tests [1].

People disagree on how isolated the unit should be. Solitary tests replace collaborators with test doubles, while sociable tests let the unit use real collaborators. Fowler prefers sociable tests but still reaches for doubles when a collaboration is awkward, such as a remote service [1].

What does a unit test look like?

Python's unittest framework was originally inspired by JUnit. Its documentation defines four concepts: the test fixture, the test case, the test suite and the test runner that executes tests and reports the outcome [2]. In its basic example, the test_upper method of TestStringMethods checks that "foo" becomes "FOO" when upper-cased [2]:

python
def test_upper(self):
    self.assertEqual('foo'.upper(), 'FOO')

Test methods are picked up by the test prefix in their names, and using assertEqual lets the runner collect every result into a report [2].

How fast should unit tests be?

Because they are quick, programmers run them often; Fowler runs his several times a minute. His rule is that a suite should be fast enough that you are never put off running it. Kent Beck's rule of thumb is that the commit suite should take no more than ten minutes [1].

Frequently asked questions

How is a unit test different from an integration test?

A unit test focuses on a small part of the system and runs fast. An integration test checks that several parts work correctly together.

Which tools are used for unit testing?

Most languages have a standard framework. Python ships unittest in its standard library, and Java has JUnit, which inspired it.

Sources

  1. Unit Test — martinfowler.com
  2. unittest - Unit testing framework — Python documentation