Reputation:
I have a question about how to test 2 classes which have a dependency between each other, but cannot be unit tested together. I am not able to create a short enough code example so I will attempt to explain it with hypothetical classes. Sorry if this is too confusing, but I am still trying to come up with a succinct example.
In this example we are concerned with 4 different classes: ObjectCreator, ObjectUser1, ObjectUser2 and Object. In the unit tests for ObjectUser1 and ObjectUser2 each explicitly construct an instance of Object to be used. ObjectCreator also has unit tests to ensure the "correct" construction of an instance of Object. All the unit tests pass successfully. Now, a bug in ObjectUser1 is found which was not exposed in the unit tests. This bug is due to an incompatibility between how ObjectCreator creates the object and how ObjectUser1 makes use of it. This bug does not exist in ObjectUser2. The fix for the bug is to change the way ObjectCreator will construct the object. The problem I am facing is that when I change ObjectCreator all the unit tests pass again, but I know that the new change has broken ObjectUser2 (The unit tests pass for ObjectUser2 because of the way Object is constructed for the unit test). Let's assume that I do not want to use ObjectCreator in the unit tests for ObjectUser1 and ObjectUser2 for complexity reasons.
Is this a common problem in unit testing? What is the best way to test the dependency if they can't be unit tested together? Any help on this would be appreciated.
Upvotes: 0
Views: 378
Reputation: 14661
It looks like you have not adequately split the dependency logic from the application logic as Object A creates Object B. You want to chop that out so A has a reference to a provider of some sort that creates Object Bs.
The route I would take would be to use Dependency Injection to separate the dependency construction logic from the application logic. However switching to a DI framework may be a large undertaking for your project. You have other options available to you, include a simple static factory method, as long as you add hooks into the method to force it to return what you need it to return.
Once the two have been separated it is a simple case of mocking Object B.
Upvotes: 1
Reputation: 49832
It sounds to me like your objects are too tightly coupled, and could do with being separated. Could you be reusing Object in a way that makes things difficult to decouple, and perhaps need two separate objects?
Upvotes: 0
Reputation: 32629
When testing class B, Mock A. So you will get the results you want from A. But B will still depend on it.
You'll be able to unit test as you want. And you keep your dependency.
Upvotes: 2