mosquito87 mosquito87 - 8 days ago 6
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(...)


and

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


but both didn't work.

Answer

Assuming

var _invoiceRepositoryMock = new Mock<InvoiceEntity>();

Then setup can be

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

or more specific

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