Search code examples
unit-testingtdd

What should a "unit" be when unit testing?


On Proggit today I was reading the comment thread on a submission entitled, "Why Unit Testing Is A Waste of Time".

I'm not really concerned with premise of the article so much as I am with a comment made concerning it:

The stem of the problem is that most “units” of code in business software projects are trivial.

Change the size of the unit until it is no longer trivial? Who the hell defined the unit of code as a single function or method anyway!?

and

Well, some of the guys I worked with wanted to define a unit as single functions. It was completely stupid. My favorite definition of "unit" is: the smallest piece of the code that can be usefully tested.

Are we spending too much time just to Mock out some objects and test a trivial piece of code and not really adding anything of value?

What should a "unit" be when Unit Testing? Are function level tests too granular?


Solution

  • It may seem trivial to quote Wikipedia, but I think it's very succinct and accurate in this case:

    A unit is the smallest testable part of an application.

    This seems to agree with the comment in your question that a unit is "the smallest piece of the code that can be usefully tested". In other words, make the unit as small as you possibly can such that it still makes sense to the developer/tester by itself.

    Often you will want to test parts of a project in isolation, and then test how they interact in combination. Having various tiers (levels) of unit testing is often a wise thing to do, as it helps insure that your code is working as it should on all levels, from individual functions up to entire self-contained tasks. I personally do not believe that it is wrong, or even unhelpful, to test individual functions, so long as they are doing something useful in themselves, which can often be the case.

    To be quite honest, there is no definite or rigorous definition of a "unit" in "unit testing", which is precisely why the vague term "unit" is used! Learning what needs to be tested and at what level is a matter of experience, and quite often, simply trial and error. It may sound like a slightly unsatisfying answer, but I believe it is a sound rule to follow.