How to properly fake IQueryable<T> from Repository using Moq?

c#, moq, nunit, unit-testing

Solution

Change mock setup to

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

Problem

I have a class that takes an IRepository in its constructor like this ... ``` public class UserService { public IRepository<User> _repo { get; set; } public UserService(IRepository<User> repo = null) { _repo = repo ?? new UserRepository(); } ``` and has a method that looks like this ... ``` public bool IsUserActive(email string) { //The method actually does more but to keep it simple lets imagine // it does this User user = _repo.Find(u => u.Email == email).First(); return user.IsActive; } ``` The IRepository looks like this. ``` public interface IRepository<T> : IDisposable where T : IEntity { void InsertOrUpdate(T entity); void Delete(T entity); IQueryable<T> Find(Func<T, bool> query); T Find(int id); void Save(); } ``` I would like to test the `IsUserActive` method and make sure it returns false if the `IsActive` field of the user is false, and vice versa. I'm trying the following ... ``` [Test] public void IsUserActive_EmailThatWillReturnInactiveUser_ReturnsFalse() { //Arrange var fakeUserRepo = new Mock<IRepository<User>>(); var query = new Func<User, bool>(u => u.Email == "AnyString"); var listOfMatchingUsers = new List<User>() { new User { Email = "AnyString", IsActive = False } }; IQueryable<User> queryableUsers = listOfMatchingUsers.AsQueryable(); fakeUserRepo.Setup(r => r.Find(query)).Returns(queryableUsers); var userService = new UserService(fakeUserRepo.Object); //Act var result = userService.IsUserActive("AnyString"); //Assert Assert.IsFalse(result); } ``` When I run in NUnit I get the Error "Sequence Contains No Elements" on this line ``` var result = userService.IsUserActive("AnyString"); ``` Where am I going wrong?

Original source