mosquito87 mosquito87 - 1 year ago 110
C# Question

Mocking method of generic repository

I'm trying to mock the following method using 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 = "");


It's initialized this way:

_invoiceRepository = new SqlGenericRepository<InvoiceEntity>(Context);

No matter of the parameter, the method should always return a list.

I tried

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


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

but both didn't work.

Answer Source


var _invoiceRepositoryMock = new Mock<InvoiceEntity>();

Then setup can be

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

or more specific

    .Setup(m => m.Get(It.IsAny<Expression<Func<InvoiceEntity, bool>>>(), null, string.Empty))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download