8

I am new to unit test and DI, and can't find a simple way of calling a method inside a class that is designed with dependencies injection.

This is my class

public class AgentProvisioningServiceHelpher : IAgentProvisioningServiceHelpher
{
    private readonly IExcelParser _excelParser;
    private readonly SupervisorDbContext _SupervisorDbContext;
    private readonly SchedulerNoTrackingDbContext _SchedulerDbContext;

    // constructor
    public AgentProvisioningServiceHelpher(IExcelParser excelParser, SupervisorDbContext supervisorDbContext, SchedulerNoTrackingDbContext SchedulerDbContext)
    {
        _excelParser = excelParser;
        _SupervisorDbContext = supervisorDbContext;
        _SchedulerDbContext = SchedulerDbContext;
    }

    // Function that I want to call in unit test
    public int SimpleMethodToTest(int InputId) 
    {
        return InputId + 1;
    } 
}

This is my interface code

    public interface IAgentProvisioningServiceHelpher
    {
        int SimpleMethodToTest(int InputId);
    }

This is my unit test code, I am using Xunit

public class UnitTest1
{
    private IAgentProvisioningServiceHelpher _sut; 
    private IExcelParser _excelParser;
    private SupervisorDbContext _DBcontext1;
    private SchedulerNoTrackingDbContext _DBcontext2;

    public UnitTest1(IExcelParser excelParser, SupervisorDbContext DBcontext1, SchedulerNoTrackingDbContext DBcontext2, IAgentProvisioningServiceHelpher sut)
    {
        _excelParser = excelParser;
        _DBcontext1 = DBcontext1;
        _DBcontext2 = DBcontext2;
        _sut = sut;
    }

    [Fact]
    public void SimpleMethodToTest_Shall_ReturnPlus1()
    {
        // Arrange
        int Input_Int = 1;

        // Act
        // I try to tell the interface to map with the class I want to test
        IAgentProvisioningServiceHelpher _sut = new AgentProvisioningServiceHelpher(_excelParser, _DBcontext1, _DBcontext2);

        // Then I try to call the interface method 
        var result = _sut.SimpleMethodToTest(Input_Int);

        // Assert
        Assert.Equal(2, result);
    }
}

When I try to run the test, Visual Studio complains with this error - how can I fix this?

UnitTest1.cs line 33

The following constructor parameters did not have matching fixture data: IExcelParser excelParser, SupervisorDbContext DBcontext1, SchedulerNoTrackingDbContext DBcontext2, IAgentProvisioningServiceHelpher sut

3

2 Answers 2

12

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.

0

You are not using a Dependency Injection container, so nothing is injecting your dependencies.

You need to instante each dependency by yourself and pass it to the constructor.

Because this problem to test class that uses IoC I created the package BuddyInjector to inject your dependencies in your tests.

BuddyInjector is a small and simple dependency injector. The main propose is just prepare the dependencies and keep simple to override each dependency per test when nedded.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.