2016-04-21 68 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>());