Moq设置返回null

时间:2013-06-14 21:42:22

标签: moq

我使用Moq设置我的模拟对象:

var accountRepositoryMock = new Mock<IGenericRepository<Account>>();
accountRepositoryMock.Setup(r => r.SingleOrDefault(a => a.AccountId == It.IsAny<long>())).Returns(new Account { AccountId = 99999999, Valid = true });

var unitOfWorkMock = new Mock<IUnitOfWork>();
unitOfWorkMock.SetupGet(unitofwork => unitofwork.AccountRepository).Returns(accountRepositoryMock.Object);

然后我将它传递给我的服务:

 IQuickPayService quickPayService = new QuickPayService(unitOfWorkMock.Object);
 Account account = quickPayService.ValidateAccount(accountId);

当我在客户端代码中执行此操作时,我将帐户视为空

public class QuickPayService : IQuickPayService
{
   public QuickPayService(IUnitOfWork unitOfWork)
   {
        _unitOfWork = unitOfWork;
   } 

   public AccountStatus ValidateAccount(long accountId)
   {
        var account;
        using (_unitOfWork)
        {
           account = _unitOfWork.AccountRepository.SingleOrDefault(acc => acc.AccountId == 99999999);

        }
        return account;
   }

}

关于我做错的任何想法?

1 个答案:

答案 0 :(得分:2)

假设您的界面声明类似于以下内容:

public interface IGenericRepository<T>
{
    T SingleOrDefault(Func<T, bool> predicate);
}

Setup中指定委托将无效。见Issue 300: Mocking Method with Delegate as Parameter。我尝试时得到NotSupportedException

相反,试试这个:

accountRepositoryMock.Setup(r => r.SingleOrDefault(It.IsAny<Func<Account, bool>>()))
    .Returns(new Account { AccountId = 99999999, Valid = true });

Moq framework Func<T,T>

有一个更详细的例子