简体   繁体   中英

Mocking LINQ Expressions - Moq

How do I mock something that is - Expression> using Moq?

I'm trying to mock a call to my repo layer that takes in a LINQ Expression for constructing a query. I'm trying the below syntax but it fails. The SearchFor method doesn't get called.

var array = new Employee[1];

array[0] = new Employee() { ID = 1234, Name = "Test" };

MockEmployeeRepo.Setup(x => x.SearchFor(It.IsAny<Expression<Func<Employee, bool>>>()))
            .Returns(array.AsQueryable);

var list = EmployeeService.GetEmployees("Test");

MockEmployeeRepo.Verify(x => x.SearchFor(x1 => x1.Name == "Test"), Times.Once());

Assert.AreEqual("Test", list[0].Name);

Here the GetEmployees method looks like below.

public IEnumerable<Employee> GetEmployees(string name)
{
    return repo.SearchFor(x => x.Name == name);
}

Moq does not supports with Expression function so here is the best solution. Use this nuget package Moq.Expression

// import namespace
using MoqExpression;

// it will work
MockEmployeeRepo.Setup(x => x.SearchFor(MoqHelper.IsExpression<Employee>(s => s.Name.Equals("Test")))).Returns(array.AsQueryable);

For more documentation: https://github.com/ovaishanif94/Moq.Expression

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM