Search code examples
c#unit-testingmoqunity-container

How to Mock a named constructor dependency


I have an MVC controller that has the following signature:

 public AccountController(
            IRulesFacade rulesFacade,
            [Dependency("personAppClient")] IAppClient personAppClient,
            [Dependency("notificationsClient")] IAppClient notificationsClient, 
            ITransformer<ExpandoObject> transformer)

You will notice that there are two CTOR properties which are the same Interface type but which are named differently.

In my Unity configuration I have the following lines of code:

 container.RegisterType<IAppClientConfigProvider, AppClientConfigProvider>("personAppClient", new InjectionConstructor(
                new ResolvedParameter<IAppClient>("personAppClient"),
                personBaseUrl));
container.RegisterType<IAppClientConfigProvider, AppClientConfigProvider>("notificationsClient", new InjectionConstructor(                    
                new ResolvedParameter<IAppClient>("notificationsClient"), 
                notificationsBaseUrl));             

In my UnitTest I have the following with some related Setup code:

MockAppClient = new Mock<IAppClient>();

MockAppClient.Setup(ac => ac.AddAsync<ExpandoObject>(It.IsAny<ExpandoObject>()))
             .Returns(() => Task.FromResult(User));

My question is how do I create a Mock that can provide the necessary "name" for the Dependency?


Solution

  • Create two separate mocks of the dependencies and pass that to the SUT

    // Arrange
    var personAppClientMock = new Mock<IAppClient>();
    personAppClientMock.Setup(_ => _.AddAsync(It.IsAny<ExpandoObject>()))
                       .ReturnsAsync(User);
    
    var notificationsClientMock = new Mock<IAppClient>();
    notificationsClientMock.Setup(_ => _.AddAsync(It.IsAny<ExpandoObject>()))
                           .ReturnsAsync(SomeOtherObject);
    
    //...other related setup code
    
    var sut = new AccountController(
                      rulesFacadeMock.Object, 
                      personAppClientMock.Object, 
                      notificationsClientMock.Object, 
                      transformerMock.Object);
    
    // Act
    //...