简体   繁体   English

用 List 模拟一个方法<int>作为参数并使用 Moq 返回 List&lt;&gt;

[英]Mock a method with List<int> as parameter and return List<> with Moq

In my test, I defined as data a List<IUser> with some record in.在我的测试中,我将List<IUser>定义为数据,其中包含一些记录。

I'd like setup a moq for the method GetList, this method receives a List<int> as the parameter.我想为 GetList 方法设置最小起订量,此方法接收List<int>作为参数。 This is a list of Ids;这是一个 Id 列表; I'd like to return the IUser list with these Ids in the List<IUser>我想在List<IUser>返回带有这些 Id 的 IUser 列表

I tried this but I don't find the right Returns syntax我试过了,但我没有找到正确的 Returns 语法

Mock<IUsers> mockUserRepository = new Mock<IUsers>();
_mockUserRepository.Setup(m => m.GetListAll(It.IsAny<List<int>>())).Returns(????????);

I tried something like this :我试过这样的事情:

_mockUserRepository.Setup(m => m.GetListAll(It.IsAny<List<int>>())).Returns(u =>_users.Contains(???));

Thanks,谢谢,

class User : IUser
{
    public int Id { get; set; }
    public string Firsname { get; set; }
    public string Lastname { get; set; }
}

interface IUser
{
    int Id { get; set; }
    string Firsname { get; set; }
    string Lastname { get; set; }
}

interface IAction
{
    List<IUser> GetList(List<int> listId);
}

class Action : IAction
{

    public List<IUser> GetList(List<int> listId)
    {
        //....
    }
}

Try this:尝试这个:

mock.Setup(users => users.GetListAll(It.IsAny<List<int>>()))
            .Returns<List<int>>(ids =>
                {
                    return _users.Where(user => ids.Contains(user.Id)).ToList();
                });

If you have more as one filter parameter you can use this example如果您有多个作为一个过滤器参数,您可以使用此示例

mock.Setup(o => o.GetListAllAsync(It.IsAny<List<int>>(), It.IsAny<string>())
 .ReturnsAsync((int[] ids, string firstname) =>
 {
   return _users
          .Where(user => ids.Contains(user.Id) && user.Firstname.Equals(firstname))
          .ToList();
 });

只需返回准备好的列表:

_mockUserRepository.Setup(m => m.GetListAll(It.IsAny<List<int>>())).Returns(_users);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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