c# – 如何在moq Repository中执行表达式?

我有IGeneric存储库有功能声明

T FindBy(表达式< Func< T,bool>>谓词);

和通用存储库类

public T FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
    {
        return _dbset.FirstOrDefault(predicate);
    }

并拥有单元测试类,
创建一个模拟存储库并将数据初始化到模拟数据库中

[TestClass]
public class ServiceTest
{
    private IClientRepository mockClientRepository;
public ServiceTest()
    {
        IList<ClientData> client = new List<ClientData>
            {
                new ClientData{ Name= "Mike", Address ="Uk" },
                new ClientData{ Name= "Jane", Address ="US" },
            };
         Mock<IClientRepository> _mockRepository = new Mock<IClientRepository>();
        _mockRepository.Setup(m => m.FindBy(It.IsAny<Expression<Func<ClientData, bool>>>())).Returns((string apiClient) =>
        {
            var data = client.Where(x => x.Hash == apiClient).FirstOrDefault();
            return data;
        });
this.mockClientRepository = _mockRepository.Object;
} 
[TestMethod]
public void IsDataFindByName()
    {
        ClientData testResult = this.mockClientRepository.FindBy(i => i.Name== "Mike");
        Assert.IsNotNull(testResult);
    }

我在运行测试时发现异常

Additional information: Object of type 'System.Linq.Expressions.Expression`1[System.Func`2[Adminportal.Entities.ClientData ,System.Boolean]]' cannot be converted to type 'System.String'.

我不知道如何通过它,

最佳答案 参数化的Returns方法期望其参数与mocked方法的参数类型相同.当表达式< Func< ClientData,bool>>是预期的时,你使用.Returns((string apiClient).只需将其改为:

.Returns((Expression<Func<ClientData, bool>> expression) =>
{
    var data = client.Where(expression.Compile()).FirstOrDefault();
    return data;
});
点赞