验证方法是使用某些linq表达式(moq)调用的 [英] Verify method was called with certain linq expression (moq)

查看:52
本文介绍了验证方法是使用某些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());

请帮助.

推荐答案

嗯,您可以通过为接口创建一个模拟方法来验证lambda是否被调用,该接口具有与lambda参数匹配的方法,并验证:

Hmmm, you can verify that the lambda is being called by creating a mock for an interface that has a method matching the lambda parameters and verifying that:

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,则它将在运行时崩溃.但是,如果它对表达式进行了简单的编译,那么您可能会不满意它.

The above might or might not work for you, depending on what Single method does with the Expression. If that expression gets parsed into SQL statement or gets passed onto Entity Framework or LINQ To SQL then it'd crash at runtime. If, however, it does a simple compilation of the expression, then you might get away with it.

我谈到的表达式编译看起来像这样:

The expression compilation that I spoke of would look something like this:

Func<Customer, bool> func = Expression.Lambda<Func<Customer, bool>>(expr, Expression.Parameter(typeof(Customer))).Compile();

编辑,如果您只是想验证该方法是使用某个表达式调用的,则可以在表达式实例上进行匹配.

EDIT If you simply want to verify that the method was called with a certain expression, you can match on expression instance.

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));
}

这篇关于验证方法是使用某些linq表达式(moq)调用的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆