如何使用Moq从存储库中正确伪造IQueryable <t>?</t>

时间:2012-10-25 16:07:52

标签: c# unit-testing nunit moq

我有一个在其构造函数中使用IRepository的类......

    public class UserService
    {
       public IRepository<User> _repo { get; set; }
       public UserService(IRepository<User> repo = null)
       {
        _repo = repo ?? new UserRepository();
       }

并且有一个看起来像这样的方法......

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;
}

IRepository看起来像这样。

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();
}

我想测试IsUserActive方法并确保如果用户的IsActive字段为false,则返回false,反之亦然。

我正在尝试以下内容......

    [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);
    }

当我在NUnit中运行时,我在这一行得到错误“序列包含无元素”

var result = userService.IsUserActive("AnyString");

我哪里错了?

1 个答案:

答案 0 :(得分:9)

将模拟设置更改为

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