문제

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
}
도움이 되었습니까?

해결책

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

}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top