【问题标题】:tdd ioc container ninject contextual bindingtdd ioc 容器 ninject 上下文绑定
【发布时间】:2017-04-12 14:34:41
【问题描述】:

在使用 ninject 的上下文绑定方面我需要一些帮助 我有这样的事情:

public interface ISound
{
    String Sound();
}

public class Cat : Animal
{
    private string category;
    private ISound sound;

    public Cat(ISound sound, int age, string name, string sex, string category)
         : base(age, name, sex)
    {
        this.sound = sound;
        this.category = category;
    }


public class CatSound : ISound
{
    public String Sound()
    {
        return "Meow";
    }
}

和实现 Sound 的完全相同的 Dog Sound 和我的绑定模块:

 public class BindingModule:NinjectModule
{
    private readonly SelectorMode _typeofsound;

    public new StandardKernel Kernel => ServiceLocator.Kernel;

    public BindingModule(SelectorMode mode)
    {
        _typeofsound = mode;
    }


    public override  void Load()
    {
        if (_typeofsound == SelectorMode.Dog)
        {
            Kernel.Bind<ISound>().To<DogSound>();
        }
        else if(_typeofsound==SelectorMode.Cat)
        {
            Kernel.Bind<ISound>().To<CatSound>();
        }
        else
        {
            Kernel.Bind<ISound>().To<HorseSound>();
        }


    }

    public class SelectorMode
    {
        public static SelectorMode Cat;
        public static SelectorMode Horse;
        public static SelectorMode Dog;


    }
}

以及我正在尝试运行的测试

public class WhenBindingCat:GivenABindingModule
        {
            [TestMethod]
            public void SouldBindItToCat()
            {
                // var kernel=new Ninject.StandardKernel(new  )
                var sut = new BindingModule(SelectorMode.Cat);

                sut.Load();



            }

它不知道我应该如何在这里断言

【问题讨论】:

    标签: c# ninject contextual-binding


    【解决方案1】:

    试试这样的:

            [TestMethod]
            public void SouldBindItToCat()
            {
                var sut = new BindingModule(SelectorMode.Cat);
                IKernel kernel = new StandardKernel(sut);
    
                Assert.IsTrue(kernel.Get<ISound>() is Cat);
            }
    

    和

    用枚举替换 SelectorMode 类

    public enum SelectorMode
    {  
        Cat, Horse, Dog   
    }
    

    【讨论】:

    • 在这个例子中,这看起来是最好的方法。另一种方法可能是围绕内核创建一个接口并将其模拟出来。这样就可以断言是否调用了正确的内核绑定。
    • 测试失败,他是DogSound类型,你觉得可能是我的SelectorMode有问题?
    • 可能你有另一个覆盖 Bind 的测试
    • @AlexandraTupu,我已经更新了答案,现在它必须有效
    • @AlexandraTupu 如果你放置 IKernel kernel = new StandardKernel(); 会怎样?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多