Verify method was called with a specific linq (moq) expression

Unable to determine 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.

+3
source share
1 answer

Hmmm, you can verify that lambda is being invoked by creating a layout for an interface that has a method that matches the lambda parameters, and checking 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 may or may not work for you, depending on what the method Singledoes with the expression. If this expression is parsed in an SQL statement or passed to the Entity Framework or LINQ To SQL, then it will be broken at run time. If, however, it performs a simple compilation of the expression, then you can get away from it.

, , :

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

Source: https://habr.com/ru/post/1759123/


All Articles