2009-11-30 83 views
6

有沒有人使用Rhino Mocks和NInject來實現自動模擬容器?自動模擬容器:Rhino Mocks和NInject

+0

我知道它應該是所有明顯的,並且但是......什麼特點你在找什麼?你可以分享更多的背景嗎? – 2009-11-30 09:47:02

回答

6

好的我自己用Moq集成作爲一個起點。這很簡單。你需要這3類:

public class AutoMockingKernel : StandardKernel 
{ 
    private readonly IMockProvider _mockProvider; 

    public void Reset() 
    { 
     Components.Get<ICache>().Clear(); 
    } 

    protected override bool HandleMissingBinding(Type service) 
    { 
     var isSelfBindable = TypeIsSelfBindable(service); 

     var binding = new Binding(service) 
     { 
      ProviderCallback = isSelfBindable 
           ? StandardProvider.GetCreationCallback(service) 
           : _mockProvider.GetCreationCallback(), 
      IsImplicit = true 
     }; 

     if (!isSelfBindable) 
      binding.ScopeCallback = ctx => null; 

     AddBinding(binding); 

     return true; 
    } 

    public AutoMockingKernel(IMockProvider mockProvider, INinjectSettings settings, params INinjectModule[] modules) 
     : base(settings, modules) 
    { 
     _mockProvider = mockProvider; 
    } 

    public AutoMockingKernel(IMockProvider mockProvider, params INinjectModule[] modules) 
     : base(modules) 
    { 
     _mockProvider = mockProvider; 
    } 
} 

internal class RhinoMockProvider : IProvider 
{ 
    public Type Type { get; private set; } 

    /// <summary> 
    /// Initializes a new instance of the <see cref="RhinoMockProvider"/> class. 
    /// </summary> 
    public RhinoMockProvider(Type type) 
    { 
     Type = type; 
    } 

    public object Create(IContext context) 
    { 
     return MockRepository.GenerateMock(Type, Type.EmptyTypes); 
    } 
} 

public class RhinoAutoMockProvider : IMockProvider 
{ 
    public Func<IContext, IProvider> GetCreationCallback() 
    { 
     return ctx => new RhinoMockProvider(ctx.Request.Service); 
    } 
} 

然後,您可以在這樣的單元測試創​​建自動嘲諷內核:

[Test] 
public void Test() 
{ 
    var kernel = new AutoMockingKernel(new RhinoAutoMockProvider()); 
    ... etc 
} 
+0

作爲一個感興趣的問題,您如何在[拆解]中管理重置觸發? – 2009-12-01 09:41:11

+0

我在拆解過程中調用Reset的所有測試裝置都使用基類。我也使用一個靜態內核容器。絕對不是理想的,但我發現這種東西永遠不會。 – cbp 2009-12-02 00:43:15