【问题标题】:How can I call setup in Moq twice in one method?如何以一种方法在 Moq 中调用两次设置?
【发布时间】:2011-07-12 14:20:53
【问题描述】:

我有一个单元测试方法需要模拟(存根?)我正在测试的类中的两个存储库方法调用。到目前为止,我完成的每个示例都显示了 Mock 的一种设置方法,但现在我需要两种。

例子:

_employeeRepositoryMock.Setup(e => e.GetEmployees())
            .Returns(new Employee[]
                     {
                        new Employee
                        {
                            Name = "John Doe"
                        }
                     });
_employeeRepositoryMock.Setup(e => e.UpdateEmployee(1)).Returns(true);

Assert.IsTrue(_employeeService.UpdateEmployeeRecords() > 0);
_employeeRepositoryMock.Verify(gr => gr.UpdateEmployee(1), Times.Exactly(1));

在这个例子中,我需要模拟两个在“UpdateEmployeeRecords()”中调用的存储库方法,但我不确定如何。

更新

解决整个问题——我忽略了一些简单的事情。我为 UpdateEmployee 传递了错误的数值,导致 Assert 失败。我将模拟中的参数更改为 It.IsAny 以使其通过。

【问题讨论】:

    标签: asp.net-mvc unit-testing moq


    【解决方案1】:

    您可以通过创建方法应返回的数据类型(在我的情况下为List<int>List<string>)并使用.Returns 返回它来实现此目的。现在,每当调用 DoSomething() 方法时,它都会返回我的 intResult 列表作为模拟数据,并在调用 DoSomethingElseThatIsReallyCool() 方法时返回 stringResult 列表:

    //Test method
    {
      List<int> intResult = new List<int>();
      intResult.Add(0);
    
      List<string> stringResult = new List<string>();
      stringResult.Add("test");
    
      _reposMock.Setup(r=>r.DoSomething()).Returns(intResult);
      _reposMock.Setup(r=>r.DoSomethingElseThatIsReallyCool()).Returns(stringResult);
    
      Assert.IsTrue(_reposMock.SomeMethod() > 0);
    }
    

    【讨论】:

    • 抱歉,我的例子太笼统了,您的答案在翻译中丢失了。请参阅我上面的编辑。我的断言失败,我怀疑这是由于第二次设置调用。
    【解决方案2】:

    您的设置方法似乎没问题。您的断言必须由于其他原因而失败。一些想法:

    1. 您是否尝试过调试测试以查看发生了什么?
    2. 1 是在 UpdateEmployee 方法中模拟的正确值吗?
    3. (请原谅我,如果这是光顾,但我以前做过)你是否通过 _employeeRepositoryMock.Object 将你的模拟传递给你的服务?

    【讨论】:

      猜你喜欢
      • 2012-06-25
      • 2012-10-04
      • 2012-07-01
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多