Unit Testing – When Should You Start Unit Testing During Development?

debuggingtestingunit testing

I'm currently learning about unit testing, specifically JUnit (with Java).

Searching the web I see many threads talking about why you should use it, what type of methods you should use it with but I can't seem to find much information on when you should implement a unit test.

Is it best to incorporate it from the very beginning of a project and then with every method you create, you add a unit test? Or is it something that it's done towards the latter stages when the logic/structure of the program is closer to completion?

Best Answer

You should write your unit tests very near to when you write your code. "Timely" is one of the five core tenets of unit testing per Clean Code. There's even an approach that advocates writing your unit tests before your code. It's called Test Driven or Test First Development, depending on who you're talking to.

In my experience, it doesn't matter too much if the tests are done first or second, as long as the tests are done before the work as a whole is considered "done". This means having the unit tests done to consider your story/task done.

Doing the tests near the time you do your code lets you:

  • Write better tests since you remember better what the code should be doing. And you remember how the code does it, making bugs quicker to fix once your unit tests find them.
  • Catch bugs earlier, before others use your code. Catching bugs earlier means they're cheaper to fix.
  • Not fall into the "oh, I'll do it later" trap.