【问题标题】:Moq: Mock interface that inherits from generic interfaceMoq:从通用接口继承的模拟接口
【发布时间】:2016-04-27 16:36:30
【问题描述】:

我有一个接口定义如下:

public interface IBaseRepository<T>
{
    IQueryable<T> All();
}

然后,我有一个扩展这个接口:

public interface IAccountRepository : IBaseRepository<AccountModel>
{
}

然而,在我的测试中,当我尝试模拟 IAccountRepository 并为 IAccountRepository.All() 调用 setup 时,Moq 不允许我使用 Returns 方法来定义结果。

var mockAccountRepository = new Mock<IAccountRepository>();
mockAccountRepository.Setup(x => x.All()).Returns(...); // "Returns" can't work here for some reason.

如何在从通用接口继承的接口上模拟基本方法?

【问题讨论】:

  • 你得到什么错误?您是否要返回 IQueryable&lt;AccountModel&gt; 以外的其他内容?
  • Moq won't allow me to use the Returns method to define a result 这是什么意思?抛出异常,编译错误?你需要更具体。
  • 附带说明一下,我会对从存储库返回 IQueryables 进行一些研究 - 它有好处,但会带来很多风险。
  • 嘎——不知道这里发生了什么。它突然起作用了。一定是VS侥幸......

标签: c# .net unit-testing moq


【解决方案1】:
mockAccountRepository.Setup(x => x.All()).Returns(new List<AccountModel>().AsQueryable());

【讨论】:

  • @DStanley,你说得对,我加了.AsQueryable()
  • 这是我尝试过的,由于某种原因,Intellisense 和编译失败了。开始随机工作。我把它归结为 VS 侥幸。
猜你喜欢
  • 2010-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多