4

Let's say I have a system composed of three classes: A,B,C that share certain dependencies.

To test A independently, I would need to create mock objects for B and C To test B independently, I would need to create mock objects for A and C etc...

So if I want to write tests for A, B, and C, I would need to create mock classes for each one of them. Am I understanding this correctly?

3 Answers 3

3

I interpret your example to mean A, B, and C are all interdependent, i.e. there are six edges in the dependency graph. Before considering how to unit test such a design, you might ask yourself whether you really need that many dependencies. It's a nice idea for a society but not for a code base. A large number of interdependencies is a forbearer of brittle, hard-to-maintain code.

1

The answer is yes, but this is often overkill. Ideally your application should have been programmed to interfaces and you should be able to choose to mock out the interfaces that allow you to test components independently.

1
  • +1 Using interfaces decouples the application making it robust enough for future changes. It also follows the "Law of Demeter" design principle eliminating dependencies
    – Aruna
    Commented Jun 8, 2011 at 22:39
0

One would want to mock dependencies. If A depended (ie used) B and C, one might need to mock B and C depending upon whether or not that particular test uses them.

The creation of a mock is also not a one-time thing. Mocks are used to test expectations and force certain behavior (eg function throwing an exception in order to test exception handling).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.