How to stub 2nd call of method?

邮差的信 提交于 2019-12-08 07:24:40

问题


With MS Fakes, is there a way to supply a method body for the first call of a stubbed method and supply a different method body for the 2nd call of the same method?

I'm testing a method that calls classA.MyMethod() twice. I've stubbed classA.MyMethod() in my unit test. But this means both calls to MyMethod() will return the same thing.

I'd like the stubbed method to do this:

public void MainMethod()
{
  var result1 = classA.MyMethod(); //return null
  ...
  var result2 = classA.MyMethod(); //return x
}

回答1:


You can modify the shim within the method call to replace it after the first one is complete:

[TestMethod]
public void TestMethod1()
{
    using (ShimsContext.Create())
    {
        Something.Fakes.ShimClassA.MethodA = () =>
        {
            Something.Fakes.ShimClassA.MethodA = () =>
            {
                return "Second";
            };
            return "first";
        };
        var f = Something.ClassA.MethodA();      // first
        var s = Something.ClassA.MethodA();      // second
        var t = Something.ClassA.MethodA();      // second
    }

    var orig = Something.ClassA.MethodA();      // This will use the original implementation of MethodA

}


来源:https://stackoverflow.com/questions/22159248/how-to-stub-2nd-call-of-method

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