2017-02-15 121 views
-1

我以嘲笑的依賴配置MockingKernel。儘管如此,Setup方法不可用。設置一個嘲笑對象注入

任何想法?

我讀過文檔。我在問一些例子。不過,我認爲文檔有點差。

編輯

我已經試過這樣:

public void Test() { 

    Core.Configuration.UserIdentity userConfiguration = Core.Configuration.UserIdentity.Create("u1", "p1"); 
    IEnumerable<Core.Configuration.UserIdentity> configurationUsers = new List<Core.Configuration.UserIdentity>() { userConfiguration }; 

    this.IoCKernel.Get<Core.Configuration.ICoreConfiguration>().UserIdentities.Returns(configurationUsers); 

    //Testing 
    Core.Kernel kernel = this.IoCKernel.Get<Core.Kernel>(); 
    kernel.Received(1).AddUser(Arg.Any<Core.Identity.UserIdentity>()); 
} 

不過,我得到這個NSubstitute.Exceptions.NotASubstituteException異常消息現在最後一行:

NSubstitute擴展方法等。 Received()只能在使用Substitute.For()和相關方法創建的對象上調用。

正如你可以看到我試圖測試AddUser方法至少被調用一次。必須根據我的Core.Kernel實現調用AddUser

回答

3

這裏有一個工作示例:

using Ninject; 
using Ninject.MockingKernel.NSubstitute; 
using NSubstitute; 
using NUnit.Framework; 

namespace ClassLibrary1 
{ 
    [TestFixture] 
    public class MyTests 
    { 
     [Test] 
     public void Test1() 
     { 
      using (var kernel = new NSubstituteMockingKernel()) 
      { 
       var substitute = kernel.Get<IDummyService>(); 
       substitute.ReturnInt().Returns(1); 

       var instance = kernel.Get<DummyClass>(); 
       Assert.AreEqual(1, instance.Calc()); 
       substitute.Received(1).ReturnInt(); 
      } 
     } 

     public interface IDummyService 
     { 
      int ReturnInt(); 
     } 

     public class DummyClass 
     { 
      private IDummyService _dummyService; 

      public DummyClass(IDummyService dummyService) 
      { 
       _dummyService = dummyService; 
      } 

      public int Calc() 
      { 
       return _dummyService.ReturnInt(); 
      } 
     } 
    } 
} 

使用下列程序包:

PM> Get-Package 

Id         Versions         ProjectName                                           
--         --------         -----------                                           
Ninject        {3.2.2.0}        ClassLibrary1                                           
Ninject.MockingKernel    {3.2.2.0}        ClassLibrary1                                           
Ninject.MockingKernel.NSubstitute {3.2.2.0}        ClassLibrary1                                           
NSubstitute       {1.10.0.0}        ClassLibrary1                                           
NUnit        {3.6.0}         ClassLibrary1                                           
+0

感謝亞歷山大。我試過現在在帖子上添加的代碼。然而,我收到一個異常消息... – Jordi

+0

@Jordi你會得到什麼異常?你能分享更多細節嗎? –

+0

異常類型是'NSubstitute.Exceptions.NotASubstituteException'... – Jordi