简体   繁体   中英

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

I am developing an ASP.NET MVC project. I am doing unit testing to each component. I am using Moq to mock my repositories. But I am having a problem in mocking a function.

This is my test method:

[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
}

As you can see in the above code I commented where the problem is. Actually how I want to mock is I pass a parameter to function, then returns will retrieve one of the regions by parameter passed to function using as index of array.

This is an idea of what I want:

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

How can I retrieve the parameter passed to mock function from returns?

See here for a possible solution.
Basically you can just use a lambda expression inside your Returns function, providing the "Any"-Parameters. Like this:

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

Something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM