我有具有功能声明的IGeneric存储库
T FindBy(Expression<Func<T, bool>> predicate);
和Generic Repository Class
public T FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
{
return _dbset.FirstOrDefault(predicate);
}
并拥有单元Test class, 创建一个模拟存储库并将数据初始化到模拟数据库
[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'.
我不知道如何传递它,
答案 0 :(得分:2)
参数丰富的Returns
方法期望其参数与mocked方法的参数类型相同。如果需要.Returns((string apiClient)
,请使用Expression<Func<ClientData, bool>>
。只需将其更改为:
.Returns((Expression<Func<ClientData, bool>> expression) =>
{
var data = client.Where(expression.Compile()).FirstOrDefault();
return data;
});