起订量设置返回 null

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

}

关于我做错了什么有什么想法吗?

最佳答案

假设您的接口(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/

相关文章:

c# - 如何模拟返回的模拟对象的方法?

c# - 有没有办法检查模拟是否已为成员设置?

c# - MS Test 单元测试引发事件内容

unit-testing - 如何使用 Moq 模拟 Microsoft.Extensions.Logging

c# - Moq 设置 : ability to pass a value or It. IsAny<T>() 取决于条件

c# - 模拟具体类时如何设置属性

c# - Moq - 无法遍历隐藏的 IEnumerable

c# - 使用 Moq 验证使用不同状态的对象的方法调用

c# - 最小起订量测试无效方法

unit-testing - 无法加载文件或程序集“Moq,4.2.1502.911”或其依赖项之一