2017-04-12 70 views
2

我需要一些帮助,使用情境与ninject 结合我有这样的事情:TDD IoC容器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"; 
    } 
} 

和一模一样的狗声音谁implemets声音 和我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; 


    } 
} 

和测试我试图运行

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

       sut.Load(); 



      } 

而且不知道我应该怎么断言这里

回答

1

尝试是这样的:

 [TestMethod] 
     public void SouldBindItToCat() 
     { 
      var sut = new BindingModule(SelectorMode.Cat); 
      IKernel kernel = new StandardKernel(sut); 

      Assert.IsTrue(kernel.Get<ISound>() is Cat); 
     } 

通过枚举

public enum SelectorMode 
{ 
    Cat, Horse, Dog 
} 
+0

更换SelectorMode类在这个例子中,这看起来就像做最好的方法一样。另一种方法可能是在内核周围创建一个接口并将其模拟出来。通过这种方式,可以断言是否调用了正确的内核绑定。 –

+0

测试失败,他是DogSound类型,你认为这可能是我的SelectorMode中的一个问题? –

+0

也许你已经重写绑定 – gabba