The main reason for writing code in accordance with the Injection Dependency pattern and using IoC infrastructures is to get test code. However, using an IoC container in test code will produce the opposite result. From your question, I see that you are already experiencing this.
This is especially true when using the Locator (SL) pattern rather than the dependency pattern (DI). Using the SL template, a class calls an IoC container (or an abstraction of such a container) directly, instead of providing the class with the dependencies it needs (using constructor injection). Since classes call a container directly, you need to configure this container in a test environment. This is painful because test configurations or fake objects often become very complex, because you often want to influence the fake behavior on each test basis, while maintaining all thread safety, because test environments can run your tests in parallel (MSTest does this). I know that in the past I wrote some crazy test code with a stream before I found out that I was doing all this wrong: - (.
Therefore, you must use the DI pattern in your application code, and in your tests you must manually connect these dependencies. For example, when testing the HomeController class, which depends on the ICustomerService class, usually you should have a CreateController() or CreateValidController factory CreateValidController in your test class that centralizes the creation of this HomeController saves you from writing these dependencies in each test and thus creating a nightmare for service in your test code. In this factory method, you enter, for example, the FakeCustomerService class manually, doing something like this:
private static HomeController CreateController( InMemoryDataMapper mapper) { var uowFactory = new FakeNorthwindUnitOfWorkFactory() { UnitOfWork = new NorthwindUnitOfWork(mapper); }; return new HomeController(new FakeCustomerService(uowFactory)); }
What this factory method looks like, of course, depends (not a pun) on how the dependency structure of the HomeController looks.
In short, do not try to inject dependencies in test code in the same way you want to do in application code. Not only is this very difficult to do in test environments, it will mean that you must configure your IoC infrastructure for your test environment, in which case you will encounter a failure. Unfortunately, I speak from experience.
Steven
source share