C# – Having a TestContext to test methods instead of Dependency Injection

cdependency-injectionunit testing

I am working on a legacy code base and I need to find a way to write unit tests for this project.

The project has a three layer architecture (UI-Biz-DAL as we call them) and DAL is totally implemented using ADO.Net and Typed-Datasets and it is full of SQL Scripts.

Our Biz classes have methods that are responsible for doing business logic stuffs and they are dependent on other helper classes and DAL classes.

I know I can use DI to inject these classes to my Biz classes but I think that I should change a lot of code. Here's a solution that I can think of :

There's this TestContext class that acts as a container and can contain mock objects for tests but it does not have anything when it comes to run the actual code so that real objects can be used instead , here is an example :

var dal=TestContext.Current.Resolve<IMyDAL>(@default:new MyDal());

as you can see Resolve method accepts an argument of type IMyDAL that will be used in case of not running our tests.

First I would like to know what do you think about this solution

Second I am still thinking about a way to test SQL scripts that are hardcoded in our code base . How can I test them ?

Best Answer

What you're suggesting is homebrewed DI tightly coupled to each business object and auto-wiring the current behavior.

Just. no. Use a real DI solution, and auto-wire THAT to the legacy DAL.

Change the code. You're writing tests here, man, that's the Lord's work.