如何在 ASP.NET MVC 单元测试中从 Moq 中的 mock returns 检索参数值

How to retrieve value of parameters from returns of mock in Moq in ASP.NET MVC unit test

我正在开发一个 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
}

正如你在上面的代码中看到的,我评论了问题所在。实际上我想模拟的是我将一个参数传递给函数,然后 returns 将通过传递给函数的参数检索其中一个区域作为数组的索引。

这是我想要的想法:

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

如何从 returns 检索传递给 mock 函数的参数?

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

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

像这样:

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]);