使用某些linq表达式(moq)调用验证方法
问题描述:
找不到语法。使用某些linq表达式(moq)调用验证方法
//class under test
public class CustomerRepository : ICustomerRepository{
public Customer Single(Expression<Func<Customer, bool>> query){
//call underlying repository
}
}
//test
var mock = new Mock<ICustomerRepository>();
mock.Object.Single(x=>x.Id == 1);
//now need to verify that it was called with certain expression, how?
mock.Verify(x=>x.Single(It.Is<Expression<Func<Customer, bool>>>(????)), Times.Once());
请帮忙。
答
嗯,你可以验证通过创建具有匹配的λ参数和验证的方法的接口一个模拟的拉姆达被称为:
public void Test()
{
var funcMock = new Mock<IFuncMock>();
Func<Customer, bool> func = (param) => funcMock.Object.Function(param);
var mock = new Mock<ICustomerRepository>();
mock.Object.Single(func);
funcMock.Verify(f => f.Function(It.IsAny<Customer>()));
}
public interface IFuncMock {
bool Function(Customer param);
}
以上可能会或可能不会为你工作,这取决于Single
方法用于表达式。如果该表达式被解析为SQL语句或传递到实体框架或LINQ To SQL,那么它会在运行时崩溃。但是,如果它对表达式进行了简单编译,那么您可能会忽略它。
就是我所讲的表达编纂会是这个样子:
Func<Customer, bool> func = Expression.Lambda<Func<Customer, bool>>(expr, Expression.Parameter(typeof(Customer))).Compile();
编辑如果你只是想验证该方法被称为具有一定的表达,你可以匹配的表达情况。
public void Test()
{
Expression<Func<Customer, bool>> func = (param) => param.Id == 1
var mock = new Mock<ICustomerRepository>();
mock.Object.Single(func);
mock.Verify(cust=>cust.Single(func));
}