使用LightInject和Nsu​​bstitute进行自动锁定,如何实现?

cam*_*ase 5 ioc-container automocking nsubstitute light-inject

我是两个库的新手,在承诺在大型项目中使用它之前,我需要澄清我的单元测试中的低代码工作量自动插件的选项.

在Google上花了一些时间之后我得出结论,与其他一些IOC/Mocking产品配对不同,LightInject + Nsubstitute没有现成的插件库来简化单元安排阶段无操作默认模拟的声明测试.

我已经阅读了关于如何使用临时增强型模拟对象覆盖LightInject容器的LightInject文档,仅用于单元测试的范围,但是单元测试可能触及的所有无操作默认隔离模拟如何.有没有办法在LightInject容器中自动创建它们?

我正在寻找的内部IOC容器行为是:

public class LightInject.ServiceContainer
{
..

  public T GetInstance<T)
  {
     if (( this.RegisteredInterfaces.Any( i => i.Itype == T ) == false )
     && ( this.TemporaryUnitTestOverrides.Any( i => i.Itype == T ) == false ))
     && ( /* this container is configured with an automocking delegate */ ))
          return autoMockCreatorDelegate<T>.Invoke();
  }
Run Code Online (Sandbox Code Playgroud)

看起来LightInject的IProxy和Interceptors提供了一些内部模拟对象构建块,但是Nsubstitute库是完整的功能.

澄清我的意思默认不做任何模拟和增强模拟.

   // default do nothing mock
   var calculator = Substitute.For<ICalculator>();

   // Enhanced mock that will return 3 for .Add(1,2)
   var calculator = Substitute.For<ICalculator>();
   calculator.Add(1, 2).Returns(3);
Run Code Online (Sandbox Code Playgroud)

显然,第二种增强型模拟需要在每个单元测试中在本地制作.

see*_*per 8

我是LightInject的作者,非常想帮助你.

让我看看这个并回复你.同时,您可能希望在LightInject.AutopMoq中查看此库, 这是对LightInject容器的第三方贡献.它使用Moq而不是NSubstitute,但一般概念应该与您要求的类似.

话虽这么说,我前段时间做了一些工作,甚至进一步简化了自动锁定,并会看一下它,看看它如何与NSubstitute集成.

编辑

这是一个超级简单的自动插件实现,适用于任何"替代"框架.

using System.Diagnostics;
using LightInject;    
using NSubstitute;

public interface IFoo {  }

class Program
{
    static void Main(string[] args)
    {
        var serviceContainer = new ServiceContainer();
        serviceContainer.RegisterFallback((type, s) => true, request => CreateMock(request.ServiceType));            
        var foo = serviceContainer.GetInstance<IFoo>();
        Debug.Assert(foo is IFoo);
    }

    private static object CreateMock(Type serviceType)
    {
        return Substitute.For(new Type[] { serviceType }, null);                                            
    }
}
Run Code Online (Sandbox Code Playgroud)

最好的祝福

伯恩哈德里希特