【问题标题】:Using Moq to mock some constructor arguments and letting Ninject take care of the rest?使用 Moq 模拟一些构造函数参数并让 Ninject 处理其余部分?
【发布时间】:2015-02-09 20:04:30
【问题描述】:

我的服务在构造函数中采用了一堆参数,这些参数通常由 Ninject 注入。在编写单元测试时,我是否可以只模拟其中一个构造函数参数而让 Ninject 完成其余的工作?

【问题讨论】:

    标签: unit-testing ninject moq


    【解决方案1】:

    是的,您可以这样做。当然,您也需要注册所有其他依赖项(从您的生产代码或“手动”完成)。做吧

    ...instanciation of kernel and registration of non-mock types
    
    var fooMock = new Mock<IFoo>();
    kernel.Bind<IFoo>().ToConstant(fooMock.Object);
    
    SomeTestee testee = kernel.Get<SomeTestee>();
    

    但是,如果 IFoo 已经被生产代码绑定,您可以使用 Rebind 替换绑定:

    kernel.Rebind<IFoo>().ToConstant(fooMock.Object);
    

    另一种选择是使用Ninject.MockingKernel。这提供了类似Bind&lt;IService&gt;().ToMock(); 的语法。但是你最好看看这个网站,因为在这里解释它会超出范围。

    【讨论】:

      猜你喜欢
      • 2011-02-27
      • 2011-03-17
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 2013-01-21
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多