如何模拟命名构造函数依赖
How to Mock a named constructor dependency
我有一个具有以下签名的 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));
在我的单元测试中,我有以下一些相关的设置代码:
MockAppClient = new Mock<IAppClient>();
MockAppClient.Setup(ac => ac.AddAsync<ExpandoObject>(It.IsAny<ExpandoObject>()))
.Returns(() => Task.FromResult(User));
我的问题是如何创建一个可以为依赖项提供必要 "name" 的 Mock?
创建两个独立的依赖项模拟并将其传递给 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
//...
我有一个具有以下签名的 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));
在我的单元测试中,我有以下一些相关的设置代码:
MockAppClient = new Mock<IAppClient>();
MockAppClient.Setup(ac => ac.AddAsync<ExpandoObject>(It.IsAny<ExpandoObject>()))
.Returns(() => Task.FromResult(User));
我的问题是如何创建一个可以为依赖项提供必要 "name" 的 Mock?
创建两个独立的依赖项模拟并将其传递给 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
//...