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

20,240

Try this:

mock.Setup(users => users.GetListAll(It.IsAny<List<int>>()))
            .Returns<List<int>>(ids =>
                {
                    return _users.Where(user => ids.Contains(user.Id)).ToList();
                });
Share:
20,240
Kris-I
Author by

Kris-I

.NET Consulting

Updated on October 06, 2020

Comments

  • Kris-I
    Kris-I over 3 years

    In my test, I defined as data a List<IUser> with some record in.

    I'd like setup a moq for the method GetList, this method receives a List<int> as the parameter. This is a list of Ids; I'd like to return the IUser list with these Ids in the List<IUser>

    I tried this but I don't find the right Returns syntax

    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)
        {
            //....
        }
    }