2016-04-21 34 views
4

我有一个自定义的IOC容器,它接受接口和具体类型作为参数注册。在我的项目中,我已经注册了下面代码中提到的配置。你可以帮助我如何使用NSubstitute在单元测试项目中注册吗?使用Nsubstitute注册或配置IOC容器

IOC -Conatincer.cs

Register<Intf, Impl>(); 

应用 - Configuration.cs

Register<ICustomer,Customer>(); 

单元测试应用 - CustomerTest.cs

Register<ICustomer,StubCustomer>(); -I want something like this 
var substitute = Substitute.For<ICustomer>(); but It provides something like this 

回答

0

我不认为你可以有具体的实例由Unity解析,然后在其上提供NSubstitute属性/方法。

因为你的意图是做单元测试,所以你需要使用NSubstitue分解的实例,因为只有在那个实例中你才能够配置属性/方法来返回对象或者检查是否收到了调用。

0

存在使用像混凝土类,作为一种解决方法增加了一个重载的方法对寄存器(),以及作为参数传递

Container.cs

public class IOCContainer 
{ 
    static Dictionary<Type, Func<object>> registrations = new Dictionary<Type, Func<object>>(); 
    public static void Register<TService, TImpl>() where TImpl : TService 
    { 
     registrations.Add(typeof(TService),() => Resolve(typeof(TImpl))); 
    } 
    public static void Register<TService>(TService instance) 
    { 
     registrations.Add(typeof(TService),() => instance); 
    } 
    public static TService Resolve<TService>() 
    { 
     return (TService)Resolve(typeof(TService)); 
    } 
    private static object Resolve(Type serviceType) 
    { 
     Func<object> creator; 
     if (registrations.TryGetValue(serviceType, out creator)) return creator(); 
     if (!serviceType.IsAbstract) return CreateInstance(serviceType); 
     else throw new InvalidOperationException("No registration for " + serviceType); 
    } 
    private static object CreateInstance(Type implementationType) 
    { 
     var ctor = implementationType.GetConstructors().Single(); 
     var parameterTypes = ctor.GetParameters().Select(p => p.ParameterType).ToList(); 
     var dependencies = parameterTypes.Select(Resolve).ToArray();    
     return Activator.CreateInstance(implementationType, dependencies); 
    } 
} 

Configuration.cs的没有直接的方法

IOCContainer.Register(Substitute.For<IProvider>()); 
IOCContainer.Register(Substitute.For<ICustomer>());