Dependency Injection, Unit Testing, and Information Hiding
dependency-injection, information-hiding, unit-testing
Solution
[Disclaimer: I work at Typemock]
You have three alternatives:
- Create an internal method that sets the Bar class - using InternalVisibleTo in the assemblyInf.cs file you can enable your tests to set that class.
- Use DI to inject the Bar class, during test change that class with a dummy or fake.
- Use Faking/Mocking framework like Typemock Isolator (.NET) that enable you to set fake behavior on objects created within another class using `Isolate.Swap.NextInstance<Bar>.With(fakeBar);`
Problem
Suppose you have a class Foo with private member of type Bar. You don't want users to know that Foo's implementation contains a Bar and you don't want users to be able to create their own Bar and pass it through Foo's constructor, any other method, or a configuration file. Edit: Bar is also problematic in that it accesses resources outside the control of your test environment such as a special database, network connection, or another process. What do you do when you also want to be able to unit test Foo? Is dependency injection still possible? Does this mean Bar and Foo are too tightly-coupled (even though the dependency is one way) and that this situation is never an acceptable one to be in?