Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

mocking

moq

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)
    {
        //....
    }
}
like image 402
Kris-I Avatar asked Apr 03 '13 14:04

Kris-I


1 Answers

Try this:

mock.Setup(users => users.GetListAll(It.IsAny<List<int>>()))
            .Returns<List<int>>(ids =>
                {
                    return _users.Where(user => ids.Contains(user.Id)).ToList();
                });
like image 113
Vyacheslav Volkov Avatar answered Nov 20 '22 14:11

Vyacheslav Volkov