2017-04-12 60 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