How big does my project have to be to unit test?

3 min read Original article ↗

This Q&A is part of a weekly series of posts highlighting common questions encountered by technophiles and answered by users at Stack Exchange, a free, community-powered network of 90+ Q&A sites.

Lamin Sanneh Asks:

I assume that my project is decoupled enough to allow for unit testing. But how big exactly, in terms of clases and functions, does my project need to be to make unit testing worthwhile?

Is unit testing a hard necessity no matter the size of your project?

Related: “How to convince management to “invest” in unit tests?”

Your project is big enough already

gnat Answers (171 votes):

In my experience, one class and one function have been sufficient to consider the need for unit testing.

class Simple {
boolean reallySimple() {
return true; // how do we make sure it doesn't change to false?
}
}

class SimpleTest {
void assertReallySimple() {
// ensure reallySimple return value isn't changed unexpectedly
UnitTestFramework.assertTrue(new Simple().reallySimple());
}
}

Be practical

Baqueta Answers (79 votes):

I’ve never bought into the “you must unit test everything” idea, though there are certainly folks out there who have (see gnat’s answer!)

As far as I’m concerned, the main benefits of unit testing are:

  1. Helping ensure changes don’t break things.
  2. Helping you design sensible interfaces to your classes (since it forces you to be a client to your own code).
  3. Helping document how your code is expected to be used.

Basically you need to weigh the time it will take you to write & maintain tests against these factors.

Number 1 is usually sufficient to make it worth writing tests. In my experience, >95 percent of code gets modified sooner or later.

Related: “How to write “good” unit tests?”

Look for common mistakes

Mansuro Answers (14 votes):

According to Kent Beck in his answer to Stack Overflow question  “How deep are your unit tests?”, you should test the code that you tend to get wrong.

If I don’t typically make a kind of mistake (like setting the wrong variables in a constructor), I don’t test for it.

Calculate the costs

Mark Booth Answers (4 votes):

Unless you are going to write code without testing it, you are always going to incur the cost of testing.

The difference between having unit tests and not having them is the difference between the cost of writing the test and the cost of running it compared to the cost of testing by hand.

If the cost of writing a unit test is 2 minutes and the cost of running the unit test is practically 0, but the cost of manually testing the code is 1 minute, then you break even when you have run the test twice.