【问题标题】:How to retrieve value of parameters from returns of mock in Moq in ASP.NET MVC unit test如何在 ASP.NET MVC 单元测试中从 Moq 中的模拟返回中检索参数值
【发布时间】:2016-05-04 10:43:03
【问题描述】:

我正在开发一个 ASP.NET MVC 项目。我正在对每个组件进行单元测试。我正在使用 Moq 来模拟我的存储库。但是我在模拟函数时遇到了问题。

这是我的测试方法:

[TestMethod]
public void Cannot_Edit_If_Invalid_Region()
{
      Region[] regions = { 
                             new Region{
                                  Id = 1,
                                  Name = "Test 1"
                             },
                              new Region{
                                   Id = 3,
                                   Name = "Test 3"
                              },
                              new Region{
                                  Id = 4,
                                  Name = "Test 4"
                              }
                          };

    Mock<IRegionRepo> mock = new Mock<IRegionRepo>();
    mock.Setup(m=>m.Region(It.IsAny<int>())).Returns(regions[It.IsAny<int>()]); // problem is here
}

正如您在上面的代码中看到的,我评论了问题出在哪里。实际上,我想模拟的方式是将参数传递给函数,然后返回将通过传递给函数的参数检索其中一个区域,并将其用作数组的索引。

这是我想要的想法:

mock.Setup(m=>m.Region("parameter passed").Returns(regions["parameter passed"]);

如何从返回中检索传递给模拟函数的参数?

【问题讨论】:

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


    【解决方案1】:

    请参阅here 了解可能的解决方案。
    基本上,您可以在 Returns 函数中使用 lambda 表达式,提供“Any”-Parameters。像这样:

    mock.Setup(m=>m.Region(It.IsAny<int>())).Returns((int x) => regions[x]);
    

    【讨论】:

      【解决方案2】:

      类似这样的:

      Region[] regions = {
                          new Region{
                              Id = 1,
                              Name = "Test 1"
                          },
                          new Region{
                              Id = 3,
                              Name = "Test 3"
                          },
                          new Region{
                              Id = 4,
                              Name = "Test 4"
                          }
                      };
      Mock<IRegionRepo> mock = new Mock<IRegionRepo>();
      mock.Setup(x => x.Region(It.IsAny<int>())).Returns<int>((i) => regions[i]);
      
      Assert.AreEqual(mock.Object.Region(1), regions[1]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-04
        • 1970-01-01
        相关资源
        最近更新 更多