Jive Boogie
Jive Boogie

Reputation: 1265

Having trouble getting method on mocked object to return fake data

I am trying to write a test for the "MethodToTest" like shown below

Public Class UserService()
{
        private IRepository<User> _userRepo;

        public UserService(IRepository<User> userRepo = null)
        {
            _userRepo = userRepo ?? new UserRepository();
        }

        public List<string> MethodToTest(string userName)
        {
            var user = _userRepo.Find(u => u.Email == userName).First<User>();

            //Other stuff that eventually returns a List<string>
        }
}

I have the following in my test

    [Test]
    public void GetItemsByUserName_UserName_ListOfItems()
    {
        var userName = "AnyString";
        var fakeUserRepo = new Mock<IRepository<User>>();
        var fakeUserList = new List<User>()
        {
        new User()
        {
            Email = userName,
            Roles = new List<Role>()
            {
                new Role()
                {
                    Name="Role1"
                },
                new Role()
                {
                    Name="Role2"
                }
            }
        }
    };
        var fakeUserListQueryable = fakeUserList.AsQueryable<User>();
        var query = new Func<User, bool>(u => u.Email == userName);
        fakeUserRepo.Setup(u => u.Find(query)).Returns(fakeUserListQueryable);
        var userService = new UserService(fakeUserRepo.Object);
        var menu = userService.GetMenuByUserName(userName);

        //Assert Something
    }

The problem is that I can't get the find method of the _userRepo to return my fake list of users.

When running the test I get a "Sequence Contains No Elements" when executing

_userRepo.Find(u => u.Email == userName).First<User>();

in the MethodToTest. What am I doing wrong?

Upvotes: 3

Views: 143

Answers (1)

Davin Tryon
Davin Tryon

Reputation: 67336

I'm thinking that you have an equality issue on the Func<User, bool>. As you know, Moq will setup the fakeUserRepo if the query equals the actual Func inside the code you are calling. However, you are creating a new Func<User, bool> in your setup code. So, when Moq checks equality, it is checking between two different reference types and therefore not setting up the expectation.

I would try something like this:

fakeUserRepo.Setup(u => u.Find(It.IsAny<Func<User, bool>>())).Returns(fakeUserListQueryable);

See if that works and then add the username back in.

Upvotes: 1

Related Questions