Search code examples
c#ninjectcontextual-binding

tdd ioc container ninject contextual binding


I need some help with using contextual binding with ninject I Have something like this :

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";
    }
}

and exactly the same Dog Sound who implemets Sound and my bindingmodule:

 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;


    }
}

and the test i'm trying to run

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

                sut.Load();



            }

and it don't know how i should assert here


Solution

  • Try something like this:

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

    and

    replace SelectorMode class by enum

    public enum SelectorMode
    {  
        Cat, Horse, Dog   
    }