The Unit Test Trap

Photo by Suzy Hazelwood from Pexels

The trap.

It is the unit word. It is misleading. Which is the Unit? It could be a method, a class, a module, or a package. Which is the correct level? Although it looks simple, it has a lot of controversy among programmers. Most inexperienced programmers would tell you that the correct level is the class or the method level, and beyond that point, it is an integration test. Your QAs will not agree, and they would say that the integration test involves the whole application. Both forget the crucial point: all of the levels are valid targets of Unit Tests. The word unit of Unit Test implies that it looks for a bug in that unit, nothing else. So the question is, which level gives you more value? The unit can be the whole application. It satisfies the definition.

The exit.

Is the tradeoff real? Do we have to choose between having confidence in the code and our ability to correct a problem quickly? Or is there something else? Maybe something that can change the equilibrium in favor of any level, something that we failed to take into consideration.

Why do people fall into the trap?

That is the question. Why so many people write Unit Tests at levels of function or class? They may have no realized that using TDD, or a similar approach, they are quickly resolving problems. But I think that it is not the answer. I think that they cheat.

Most people like Unit Tests at the level of class or function because they cheat.

I am quite afraid that it is true. And probably, most people do not realize that they are following the path of least resistance.

Use Programmers Tests instead.

I will cover what a Programmer Test is in future articles, but meanwhile, I suggest you practice as follows:

  • Forget the one-unit limit; involve other units in a single test wisely.
  • Minimize the number of mocks; each mock diminishes your confidence.
  • Each test must satisfy a business rule; keep it in the test name.
  • Leverage in the most recent edit; write tests first and iterate frequently.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
David Rodenas, Ph. D.

David Rodenas, Ph. D.

I like to write stories about how we understand and apply software engineering, and to make us think about what we could improve.