使用某些linq表达式调用验证方法(moq)

时间:2010-08-11 12:51:37

标签: unit-testing 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());

请帮忙。

1 个答案:

答案 0 :(得分:1)

嗯,您可以通过为具有匹配lambda参数的方法并验证:

的接口创建模拟来验证是否正在调用lambda。
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方法对Expression的作用。如果该表达式被解析为SQL语句或被传递到Entity Framework或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));
}