如何模拟命名的构造函数依赖项

时间:2017-07-04 08:58:43

标签: c# unit-testing moq unity-container

我有一个具有以下签名的MVC控制器:

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

您会注意到有两个CTOR属性是相同的接口类型,但命名方式不同。

在我的Unity配置中,我有以下几行代码:

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

在我的UnitTest中,我有以下一些相关的安装代码:

MockAppClient = new Mock<IAppClient>();

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

我的问题是如何创建一个可以为依赖提供必要“名称”的模拟?

1 个答案:

答案 0 :(得分:0)

创建两个独立的依赖模拟并将其传递给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
//...