2010-08-11 48 views
3

找不到語法。使用某些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()); 

請幫忙。

回答

1

嗯,你可以驗證通過創建具有匹配的λ參數和驗證的方法的接口一個模擬的拉姆達被稱爲:

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方法用於表達式。如果該表達式被解析爲SQL語句或傳遞到實體框架或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)); 
}