When applying DI, you postpone the creation of dependencies to the last responsible moment. This means that you push the burden of creating the dependencies up as long as possible. But somewhere in the application, those dependencies need to be created.
This place where dependencies are composed is called the Composition Root. For your running application, the Composition Root will likely be the application's Main
method, or at least somewhere close the application's startup path.
Composition in Unit Testing
When writing unit tests, each unit test itself acts as a Composition Root. This means that the unit test itself (or a method it calls) is itself responsible of composition of the class that it needs to test. This means that composition is no longer postponed, and no longer pushed up. This is what you are trying to do: pushing up the responsibility of object composition to the Unit Testing framework.
Although technically, some Unit Testing frameworks would allow you to intercept the way test classes are created, letting the test framework supply the dependencies often makes little sense, because the unit test itself needs to have control over the exact dependencies being created. The test not only knows what the exact types of the dependencies should be (i.e. typically some sort of fake implementations), but also needs to configure those (fake) dependencies or query their results to assert the correctness of the test.
This means that instead of trying to inject the dependencies of AgentProvisioningServiceHelpher
inside the constructor of UnitTest1
, the SimpleMethodToTest_Shall_ReturnPlus1
method must be in control. For instance:
[Fact]
public void SimpleMethodToTest_Shall_ReturnPlus1()
{
// Arrange
int input = 1;
int expectedResult = 2;
var sut = new AgentProvisioningServiceHelpher(
new FakeExcelParser(),
new FakeSupervisorDbContext(),
new FakeSchedulerNoTrackingDbContext());
// Act
var actualResult = sut.SimpleMethodToTest(input);
// Assert
Assert.Equal(expectedResult, actualResult);
}
Creating all dependencies of the class under test in each unit test, unfortunately, becomes less and less maintainable the more tests are written. In that case it becomes a good practice to extract this composition logic out of the test, into either a helper method or helper class. The trick is in this case to make sure that a test only supplies the dependencies that are particularly interesting for that specific test, while leaving the rest blank. For instance:
[Fact]
public void Parser_should_always_be_called()
{
// Arrange
var parser = new FakeExcelParser();
AgentProvisioningServiceHelpher sut = this.CreateSut(excelParser: parser);
// Act
sut.SimpleMethodToTest(0);
// Assert
Assert.IsTrue(parser.GotCalled);
}
private AgentProvisioningServiceHelpher CreateSut(
IExcelParser excelParser = null,
SupervisorDbContext supervisorDbContext = null,
SchedulerNoTrackingDbContext schedulerDbContext = null)
{
return new AgentProvisioningServiceHelpher(
excelParser ?? new FakeExcelParser(),
supervisorDbContext ?? new FakeSupervisorDbContext(),
schedulerDbContext ?? new FakeSchedulerNoTrackingDbContext());
}
In this test, only the ExcelParser
is supplied, because it is explicitly queried during the test. The other two dependencies will be supplied with a default (probably fake) null implementation by the CreateSut
method.
In this case, the CreateSut
becomes part of the Composition Root.
Composition in Integration Testing
While writing unit tests, dependencies are typically hand-wired, as shown above. In case, however, you are writing integration tests, the number of objects involved in the test is typically larger, and needs to resemble the structure of objects that is composed in the production application (with sometimes a few dependencies replaced). Letting a single test method or test class recreate the complete object structure manually would often be cumbersome, and error prone. A change in the application's object structure could bubble through many tests and would easily result in a poorly maintainable system.
Instead, during integration testing, it's common to try to reuse the same object composition logic that the running application's Composition Root uses. When you use a DI Container to compose the application's object graphs, this typically means reusing those same DI Container registrations.
An integration test would reuse the same DI Container's configuration, mock out a few dependencies required for the integration test to run, and resolve the class under test and invoke one of its methods. But still, an integration test wouldn't get those dependencies injected from the outside, as it likely needs some control over what is created. The integration test is still its own Composition Root, even though it delegates part of the object composition to a separate Composer class (the DI Container).
Here's an example for an integration test:
[Fact]
public void Some_integration_test()
{
// Arrange
int input = 1;
int expectedResult = 2;
// Mock object
var parser = new FakeExcelParser();
// Create a valid container to resolve object graphs from
var container = TestBootstrapper.BuildContainer();
// Configure it especially for this test (note that I'm inventing a
// DI Container API here. API will very per DI Container)
container.Replace<IExcelParser>(parser);
// Resolve the SUT from the DI Container
var sut = container.Resolve<AgentProvisioningServiceHelpher>();
// Act
var actualResult = sut.SimpleMethodToTest(input);
// Assert
Assert.Equal(expectedResult, actualResult);
}
This integration test uses a TestBootstrapper
class that might be shared across integration tests:
public static class TestBootstrapper
{
public static Container BuildContainer()
{
// Request a fully configured DI Container instance from the
// actual application. This ensures that the integration test
// runs using the exact same object graphs as the final application.
var container = RealApplication.Bootstrapper.BuildContainer();
// Replace dependencies that should never be used during the
// integration tests.
container.Replace<IHardDiskFormatter, FakeDiskFormatter>();
container.Replace<ISmsSender, FakeSmsSender>();
container.Replace<IPaymentProvider, FakePaymentProvider>();
return container;
}
}
This is of course very different from unit tests, where there is a high level of isolation.