2

我使用 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);

当我在我的客户端代码中执行此操作时,我将帐户设为 null

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

}

关于我做错了什么的任何想法?

4

1 回答 1

2

假设您的接口声明类似于以下内容:

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

指定一个委托是Setup行不通的。请参阅问题 300:以委托为参数的模拟方法NotSupportedException当我尝试它时,我得到了一个。

相反,试试这个:

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

Moq 框架 Func<T,T>有一个更详细的示例

于 2013-06-14T22:37:39.637 回答