我希望测试的 C# 类接受同一接口的 IEnumerable 实例。我使用 Ninject 进行依赖注入。我如何使用 Ninject MockingKernel Moq 将模拟注入 IEnumerable
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
}
这就是我的常规绑定的样子
//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
像下面这样设置模拟只将最后一个模拟注入 Foo (应该注入 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>();
任何帮助表示赞赏。谢谢