What is a "Unit"?

While the definition can vary, a "unit" is a stand-alone piece of code.

Usually, it's a single Class.

However, few classes exist in isolation. So, you often have to mock up the classes that collaborate with your class under test.

Therefore, a "unit" (also called a "fixture") is a single testable thing -- usually a class plus mock-ups for collaborators.

You can easily test a package of related classes using the unit test technology. We do this all the time. There are few or no mocks in these fixtures.

In fact, you can test whole stand-alone application programs as single "units". We do this, also. Providing a fixed set of inputs and outputs to be sure the overall application does things correctly.


I usually define it as a single code execution path through a single method. That comes from the rule of thumb that the number of unit tests required to test a method is equal to or greater than the method's cyclomatic complexity number.


A unit is any element that can be tested in isolation. Thus, one will almost always be testing methods in an OO environment, and some class behaviours where there is close coupling between methods of that class.


In my experience the debate about "what is a unit" is a waste of time.

What matters far more is "how fast is the test?" Fast tests run at the rate of 100+/second. Slow tests run slow enough that you don't reflexively run them every time you pause to think.

If your tests are slow you won't run them as frequently, making the time between bug injection and bug detection longer.

If your tests are slow you probably aren't getting the design benefits of unit testing.

Want fast tests? Follow Michael Feather's rules of unit testing.

But if your tests are fast and they're helping you write your code, who cares what label they have?