13

我有一个类,它在它的构造函数中使用一个 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");

我哪里错了?

4

1 回答 1

9

将模拟设置更改为

fakeUserRepo.Setup(r => r.Find(It.IsAny<Func<User, bool>>()))
            .Returns(queryableUsers);
于 2012-10-25T16:17:03.787 回答