【问题标题】:Mocking method of generic repository通用存储库的模拟方法
【发布时间】:2017-04-12 04:09:24
【问题描述】:

我正在尝试使用 Moq 模拟以下方法:

public interface IGenericRepository<TEntity> where TEntity : class
{
    ...

    IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "");

}

它是这样初始化的:

_invoiceRepository = new SqlGenericRepository<InvoiceEntity>(Context);

无论参数如何,方法都应该返回一个列表。

我试过了

_invoiceRepositoryMock.Setup(m => m.Get(It.IsAny<>()).Returns(...) 

_invoiceRepositoryMock.Setup(m => m.Get(It.IsAny<Expression<Func<InvoiceEntity, bool>>>())).Returns(...)

但两者都不起作用。

【问题讨论】:

    标签: c# unit-testing mocking moq repository-pattern


    【解决方案1】:

    假设

    var _invoiceRepositoryMock = new Mock<InvoiceEntity>();
    

    然后就可以设置了

    _invoiceRepositoryMock
        .Setup(m => m.Get(
            It.IsAny<Expression<Func<InvoiceEntity, bool>>>(),
            It.IsAny<Func<IQueryable<InvoiceEntity>, IOrderedQueryable<InvoiceEntity>>>(),
            It.IsAny<string>()))
        .Returns(...);
    

    或更具体

    _invoiceRepositoryMock
        .Setup(m => m.Get(It.IsAny<Expression<Func<InvoiceEntity, bool>>>(), null, string.Empty))
        .Returns(...);
    

    【讨论】:

    • 您的“特定通话”中缺少)(在.Returns 之前)。但它正在工作。谢谢!
    【解决方案2】:

    如果你的方法是:

    IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,    
        string includeProperties = "");
    

    你的模拟必须是这样的:

    _invoiceRepositoryMock.Setup(m => m.Get(
        It.IsAny<Expression<Func<InvoiceEntity, bool>>>(),
        It.IsAny<Func<IQueryable<InvoiceEntity>, IOrderedQueryable<InvoiceEntity>>>(),
        It.IsAny<string>())).Returns(...)
    

    【讨论】:

    • TEntity 在此上下文中未知。
    • 我已经更新了我的答案。显然用 InvoiceEntity 替换 TEntity。
    【解决方案3】:

    你能像这样尝试吗,因为该方法有 4 个参数,请尝试在模拟中给出 4 个参数_invoiceRepositoryMock.Setup(m =&gt; m.Get(It.IsAny&lt;&gt;(),It.IsAny&lt;&gt;(),It.IsAny&lt;&gt;(),It.IsAny&lt;&gt;()).Returns(...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多