我希望測試的C#類接受同一接口的IEnumerable實例。我使用Ninject進行依賴注入。我怎麼會注入使用Ninject MockingKernel起訂量使用Ninject MockingKernel Moq如何爲同一接口注入多個模擬
public class Foo: IFoo
{
private readonly Dictionary<ContextType, IBar> _bars;
public Foo(IEnumerable<IBar> bars)
{
_bars= bars.ToDictionary(x => x.ContextType);
}
}
public interface IBar
{
ContextType ContextType { get; }
void DoStuff();
}
public enum ContextType
{
Local,
Site,
Test
}
嘲笑到了IEnumerable這是我的正常結合的模樣
//assume _kernel is StandardKernel
_kernel.Bind<IFoo>().To<MyFoo>();
_kernel.Bind<IBar>().To<Bar1>(); //ContextType.Site
_kernel.Bind<IBar>().To<Bar2>(); //ContextType.Local
_kernel.Bind<IBar>().To<Bar3>(); //ContextType.Test
設置如下圖所示嘲笑如何注入只剩下最後模擬成富(如應該注射3次)
//using _kernel = new MoqMockingKernel()
_kernel.Bind<IFoo>().To<MyFoo>();
var bar1Mock = _kernel.GetMock<IBar>();barMock1.Setup(m=>m.ContextType).Returns(ContextType.Site);
var bar2Mock = _kernel.GetMock<IBar>();barMock2.Setup(m=>m.ContextType).Returns(ContextType.Local);
var bar3Mock = _kernel.GetMock<IBar>();barMock3.Setup(m=>m.ContextType).Returns(ContextType.Test);
_foo = _kernel.Get<IFoo>();
任何幫助表示讚賞。謝謝
當兩次綁定到同一個接口時,實際上是_overriding_上一個綁定,而不是添加一個新綁定。所以實際上,當在代碼中的任何地方解析「IBar」時,「Bar3」類型將被實例化。你能更清楚地解釋,你想達到什麼目的? – Yura 2015-04-02 18:54:08
我有一個策略模式與IBar的ContextType屬性作爲關鍵。所以,我將多個策略(酒吧)注入Foo,並且希望在測試期間爲每個策略注入模擬。 – JRT 2015-04-02 19:18:18