2012-09-04 45 views
5

從使用Moq開始,我習慣於能夠將安裝模擬爲可驗證。正如你所知道的,當你想確保被測試的代碼實際上被稱爲依賴關係的方法時,這很方便。Visual Studio 2012假貨 - 我如何驗證被調用的方法?

例如在起訂量:

// Set up the Moq mock to be verified 
mockDependency.Setup(x => x.SomethingImportantToKnow()).Verifiable("Darn, this did not get called."); 
target = new ClassUnderTest(mockDependency); 
// Act on the object under test, using the mock dependency 
target.DoThingsThatShouldUseTheDependency(); 
// Verify the mock was called. 
mockDependency.Verify(); 

我一直在使用VS2012的「正版正貨框架」(因爲缺乏瞭解它一個更好的名字),這是很光滑,我開始喜歡它,以起訂量,因爲它似乎更富有表現力,讓Shim變得更容易。但是,我無法弄清楚如何重現與Moq的Verifiable/Verify實現類似的行爲。我在Stub上發現了InstanceObserver屬性,這聽起來可能是我想要的,但截至2012年9月4日沒有任何文檔,我不清楚如何使用它,如果它甚至是正確的。

任何人都可以在正確的方向指向我做Moq Verifiable /驗證VS2012的假貨嗎?

- 9/5/12編輯 - 我意識到問題的解決方案,但我仍然想知道是否有內置的方法來處理VS2012 Fakes。如果有人可以聲明,我會稍微等待一段時間。這是我的基本想法(道歉,如果它不編譯)。

[TestClass] 
public class ClassUnderTestTests 
{ 
    private class Arrangements 
    { 
     public ClassUnderTest Target; 
     public bool SomethingImportantToKnowWasCalled = false; // Create a flag! 
     public Arrangements() 
     { 
      var mockDependency = new Fakes.StubIDependency // Fakes sweetness. 
      { 
       SomethingImportantToKnow =() => { SomethingImportantToKnowWasCalled = true; } // Set the flag! 
      } 
      Target = new ClassUnderTest(mockDependency); 
     } 
    } 

    [TestMethod] 
    public void DoThingThatShouldUseTheDependency_Condition_Result() 
    { 
     // arrange 
     var arrangements = new Arrangements(); 
     // act 
     arrangements.Target.DoThingThatShouldUseTheDependency(); 
     // assert 
     Assert.IsTrue(arrangements.SomethingImportantToKnowWasCalled); // Voila! 
    } 
} 

- 12年9月5日結束的編輯 -

謝謝!

+0

我在這裏回答了類似的問題http://stackoverflow.com/a/13794884/333082 – cecilphillip

回答

0

儘管在複雜場景中它可能有意義,但您不必使用單獨的(Arrangements)類來存儲有關所調用方法的信息。這是一種更簡單的方法,用於驗證是否使用Fakes調用方法,該方法將信息存儲在局部變量中,而不是單獨的類的字段中。就像你的例子一樣,它意味着ClassUnderTest會調用IDependency接口的方法。

[TestMethod] 
public void DoThingThatShouldUseTheDependency_Condition_Result() 
{ 
    // arrange 
    bool dependencyCalled = false; 
    var dependency = new Fakes.StubIDependency() 
    { 
     DoStuff =() => dependencyCalled = true; 
    } 
    var target = new ClassUnderTest(dependency); 

    // act 
    target.DoStuff(); 

    // assert 
    Assert.IsTrue(dependencyCalled); 
}