views:

19

answers:

1

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.

A: 

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