【问题标题】:StructureMap: using regular parameter unless configured in ObjectFactoryStructureMap:除非在 ObjectFactory 中配置,否则使用常规参数
【发布时间】:2013-09-27 15:34:35
【问题描述】:

我觉得我正在尝试完成一些不完全是“StructureMap 方式”的事情,或者可能是,但我只是不知道该怎么做。我希望有人可以帮助我:

我正在编写一个插件,它需要有一个 Execute 方法,该方法在 IServiceProvider 中传递(由运行我的插件的应用程序提供)。
目前,我的代码如下所示:

public void Execute(IServiceProvider serviceProvider)
{
    //The serviceProvider is used to extract references to other objects it supplies:
    this.Context = serviceProvider.GetService<IPluginExecutionContext>();

    //This could go more than one level deep:
    this.Acme = this.Context.Acme;

    //Do something with this.Context and this.Acme here...
}

这适用于在生产环境中运行。但是,当我对这个插件进行单元测试时,我希望能够使用 StructureMap 插入我的 IPluginExecutionContext 或 Acme 的模拟版本。

现在,我知道如何让 StructureMap 为特定接口注册一个具体类型:

ObjectFactory.Initialize(x =>
{
    x.For<IPluginExecutionContext>()
     .Use<MockedPluginExecutionContext>();
});

但是,如果已配置,我如何让我的 Execute 实现使用此 MockedPluginExecutionContext,或者如果未配置,则使用 serviceProvider.GetService&lt;IPluginExecutionContext&gt;() 返回的值?

【问题讨论】:

    标签: c# unit-testing mocking structuremap


    【解决方案1】:

    使用 NSubstitute 我将执行以下操作以单独测试 Execute(如果这是您想要做的):

    // arrange
    var objectUnderTest = ...
    var mockPluginExecContext = new MockedPluginExecutionContext();
    var mockProvider = Substitute.For<IServiceProvider>();
    mockProvider.GetService<IPluginExecutionContext>.Returns(mockPluginExecContext);
    
    // act
    objectUnderTest.Execute(mockProvider);
    
    // assert
    Assert.IsTrue(...);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多