Unit-testing – How does TDD address interaction between objects

tddunit testing

TDD proponents claim that it results in better design and decoupled objects. I can understand that writing tests first enforces the use of things like dependency injection, resulting in loosely coupled objects. However, TDD is based on unit tests – which test individual methods and not the integration between objects. And yet, TDD expects design to evolve from the tests themselves.

So how can TDD possibly result in a better design at the integration (i.e. inter-object) level when the granularity it addresses is finer than that (individual methods)?

Best Answer

I disagree with your assumption that unit tests have to be method-scope. Unit tests don't have to be limited to testing individual methods, they can test interactions between objects too.

The difference between a unit test and an integration test is that the integration test requires some kind of external resource (database, queue, file system, etc.) to be present. The unit test would use mocks to stand in for things at the boundaries of the application.

There is an idea that unit tests should be small. The wikipedia article on Unit testing says:

In computer programming, unit testing is a method by which individual units of source code, sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures are tested to determine if they are fit for use.1 Intuitively, one can view a unit as the smallest testable part of an application. In procedural programming, a unit could be an entire module, but is more commonly an individual function or procedure. In object-oriented programming, a unit is often an entire interface, such as a class, but could be an individual method. [2] Unit tests are created by programmers or occasionally by white box testers during the development process.

So the idea of what constitutes a unit seems very flexible to me.

There's no reason a unit test can't instantiate different objects and test the results of using them together, that can be a valuable way of testing that the code is internally self-consistent.