Verify method was called with certain linq expression (moq)

为君一笑 提交于 2019-12-12 12:31:18

问题


Can't figure out the syntax.

//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());

Please help.


回答1:


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

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


来源:https://stackoverflow.com/questions/3458406/verify-method-was-called-with-certain-linq-expression-moq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!