2010-08-11 4 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()); 

도와주세요.

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

위의 힘을 또는 당신을 위해 작동하지 않을 수 있습니다 :

답변

1

흠, 당신은 람다 매개 변수와 일치하고 확인하는 방법이있는 인터페이스에 대한 모의를 작성하여 람다가 호출되고 있음을 확인할 수 있습니다 표현식에 따라 Single 메서드가 수행하는 작업에 따라 다릅니다. 해당식이 SQL 문으로 구문 분석되거나 Entity Framework 또는 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)); 
} 
관련 문제