Follow @RoyOsherove on Twitter

What does the 'unit' in 'unit test' mean?

I used to think it was a method. Then I thought it coule be several methods. then I thought it might be several classes. then I realized it changes all the time.

It means “unit of work”.

A unit of work is a use case in the system, that is initiated by a public method somewhere, and ends up with an end result. An end result can be one of three things:

  • A return value(if the public method is a function) or an exception return value
  • A noticeable change to the state of the system under test. Noticeable means that the system behaves differently to an end user than it did before. For example - adding a user changes the system behavior to allow that user to login in. 
  • A call to a 3rd party system. A 3rd party system is a dependency that we do not have control over in our test. If it touches the file system, or calls the network, or uses threads, or anything that makes our test slow, or inconsistent, it is a dependency we don’t have control over.

The third case (3rd parties) is where we end up using mock objects. In all other cases, we might have stubs to break dependencies, but our asserts will be against the system’s different states, or different return values.


Test Naming Conventions With Unit of Work

[Video] Vimming - Natural Selection in Visual Mode