How to enable unit testing on a tightly coupled business\data layers without DI?
c#, dependency-injection, unit-testing
Solution
You're not ruling out constructor injection per se, you just don't have an IOC container set up. That's fine, you don't need one. You can do Poor Man's Dependency Injection and still keep constructor injection.
Wrap the DataLayer with an interface, and then create a factory that will make `IDataLayer` objects on command. Add this as a field to the object you're trying to inject into, replacing all `new` with calls to the factory. Now you can inject your fakes for testing, like this:
interface IDataLayer { ... }
interface IDataLayerFactory
{
IDataLayer Create();
}
public class BLLayer()
{
private IDataLayerFactory _factory;
// present a default constructor for your average consumer
ctor() : this(new RealFactoryImpl()) {}
// but also expose an injectable constructor for tests
ctor(IDataLayerFactory factory)
{
_factory = factory;
}
public GetBLObject(string params)
{
using(DLayer dl = _factory.Create()) // replace the "new"
{
//BL logic here....
}
}
}
Don't forget to have a default value of the actual factory you want to use in real code.
Problem
I'm working on a project that is an older 3 tier design, any new functionality added needs to be unit testable. The problem is the business layer / data layers are tightly coupled like in the sample below. The BL just news up a data layer object... so it's almost impossible to mock up this way. We don't have any Dependency Injection implemented so constructor injection isn't possible. So what is the best way to modify the structure so that the data layer can be mocked up without the use of DI? ``` public class BLLayer() { public GetBLObject(string params) { using(DLayer dl = new DLayer()) { DataSet ds = dl.GetData(params); BL logic here.... } } } ```