Unit Testing vs TDD – Key Differences Explained

differencetddunit testing

From reading the descriptions, I understand that in TDD tests are done prior to writing the function and in Unit Testing, its done afterwards.

Is this the main difference, or the two terms can't even be compared as such. Perhaps, Unit Testing is an integrated part of TDD.

Best Answer

Unit Testing refers to what you are testing, TDD to when you are testing.

The two are orthogonal.

Unit Testing means, well, testing individual units of behavior. An individual unit of behavior is the smallest possible unit of behavior that can be individually tested in isolation. (I know that those two definitions are circular, but they seem to work out quite well in practice.)

You can write unit tests before you write your code, after you write your code or while you write your code.

TDD means (again, kind of obvious) letting your tests drive your development (and your design). You can do that with unit tests, functional tests and acceptance tests. Usually, you use all three.

The most important part of TDD is the middle D. You let the tests drive you. The tests tell you what to do, what to do next, when you are done. They tell you what the API is going to be, what the design is. (This is important: TDD is not about writing tests first. There are plenty of projects that write tests first but don't practice TDD. Writing tests first is simply a prerequisite for being able to let the tests drive the development.)