2012-09-04 108 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); 
}