Question

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
}
Was it helpful?

Solution

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

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top