我使用 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;
}
}
关于我做错了什么有什么想法吗?
最佳答案
假设您的接口(interface)声明类似于以下内容:
public interface IGenericRepository<T>
{
T SingleOrDefault(Func<T, bool> predicate);
}
在Setup
中指定委托(delegate)将不起作用。请参阅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> 有更详细的示例
关于起订量设置返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17117697/