How can I verify that a Microsoft Fakes (beta) stub/shim was called (like AssertWasCalled in Rhino Mocks)?

岁酱吖の 提交于 2019-11-28 07:22:04

问题


I'm using the beta of Microsoft Fakes in Visual Studio 11. How can I verify that a dependency's method was called by my system under test?


回答1:


As verify functionality is not included in the Microsoft Fakes Beta, the code below is a basic test for whether or not a method on a dependency was called. You could enhance the true test to test parameter values or other conditions of a proper call.

Test:

[TestMethod]
public void TestMethod1()
{
    var secondDoItCalled = false;
    var secondStub = new Fakes.ShimSecond();
    secondStub.DoIt = () => { secondDoItCalled = true; };
    var first = new First(secondStub);
    first.DoIt();
    Assert.IsTrue(secondDoItCalled);
}

Classes:

public class First
{
    readonly Second _second;
    public First(Second second) { _second = second; }
    public void DoIt() { 
        //_second.DoIt();
    }
}

public class Second {public void DoIt(){}}

Uncomment the line above to see the test pass.




回答2:


Another option that you have for doing behavioral verification with the Microsoft Fakes framework is to use the StubObserver class thats included in the Microsoft.QualityTools.Testing.Fakes.Stubs namespace. Using the framework, you generate a stub for your dependency. Then on your Stub you can set the InstanceObserver property to a new StubObserver. Using the StubObserver class, you can "query" the method calls made to your dependency. Your test method would look something like below

//Arrange
var dependency = new StubIDependency { InstanceObserver = new StubObserver() };
var sut = new SystemClass(dependency);

// Act
sut.DoSomething();

// Assert
var observer = (StubObserver)dependency.InstanceObserver;      
Assert.IsTrue(
    observer.GetCalls().Any(call => call.StubbedMethod.Name == "DoSomething"));



回答3:


Have a look to this post: http://www.peterprovost.org/blog/2012/11/29/visual-studio-2012-fakes-part-3/

Cheers



来源:https://stackoverflow.com/questions/10390422/how-can-i-verify-that-a-microsoft-fakes-beta-stub-shim-was-called-like-assert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!