c# - 为同一方法的两次调用设置两个不同的返回值

标签 c# moq

假设我有以下场景:

public interface IFoo
{
    int GetNextNumber();
}

public class Foo : IFoo
{
    public int GetNextNumber()
    {
        // returns some next number. The logic of getting the next number is not importaint
    }
}

现在,这是我要测试的方法:

public void MethodToTest(IFoo foo)
    {
        int first = foo.GetNextNumber();
        int second = foo.GetNextNumber();
    }

如何设置模拟,将其传递给 MethodToTest,以便该方法的第一次调用返回 1,第二次调用返回 2。 棘手的部分是该方法的两次调用是无法区分的,所以我不知道如何以某种“执行顺序”来设置它们

编辑:我正在使用起订量

最佳答案

您可以创建一个类来实现您的接口(interface)并在每次调用该方法时递增一个值

public class TestFoo : IFoo
{
    private static int i;
    public int GetNextNumber()
    {
        return i++;
    }
}

关于c# - 为同一方法的两次调用设置两个不同的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31477474/

相关文章:

c# - ASP.NET gridview 绑定(bind)不起作用/控件不显示

c# - 如何验证调用了一个方法?

c# - Moq 中是否有类似于 SetupGetSequence 的东西

c# - 将 excel 工作表保存到我在本地计算机上创建的特定文件夹,并将此 excel 工作表设置为只读

c# - 如何为操作实现忽略/重试/取消模式?

unit-testing - 使用 'traditional'记录/重播与Moq模型进行模拟

c# - 我可以在 Moq 中重用 It.Any 参数描述符吗

.net - 如何使用 Moq 测试 lambda 函数?

c# - 将列表转换为纯字符串,就像字符串模式一样

c# - 单元测试抽象类和其中的 protected 方法