2015-10-16 36 views
0

我想驗證一個方法的調用,該方法需要Expression<Func<T, U>>類型的參數,但我無法讓NSubstitute識別它。NSubstitute可以檢查表達式爲<T>的呼叫嗎?

public interface IFoo<T> 
{ 
    void DoThing<TProperty>(TProperty i, Expression<Func<T, TProperty>> expression); 
} 

// this almost works, but throws AmbiguousArgumentException 
myFoo.Received(1).DoThing(Arg.Is(10), Arg.Any<Expression<Func<MyClassType, long>>>()); 
+0

什麼MyObj中?你能發佈它的結構嗎? –

+0

'myObj'如何定義應該是不相關的。在我的現實世界中,'myObj'正在實現一個定義'DoThing'的接口。除了那個方法之外,它可能是完全空的。在我的測試方法中,'myObj'是一個NSubstitute替換。 – moswald

+1

我在問,因爲在我的測試中,我無法重現你所看到的行爲。但是,我對於DoThing方法簽名的假設可能是錯誤的。你能分享這個方法的定義嗎? –

回答

0

因此,儘管試圖找出爲什麼我的測試中失敗,但大衛Tchepak的工作,我才意識到我原來的問題沒有包括的事實屬性的類型是通用以及(問題已更新)。當我對David的代碼進行更改時,我開始看到與原始代碼中相同的錯誤。

我發現然而該解決方案,:

// fails with AmbiguousArgumentException 
myObj.Received(1).DoThing(Arg.Is(10), Arg.Any<Expression<Fun<MyClassType, long>>>()); 

// passes, but doesn't validate first parameter 
myObj.Received(1).DoThing(Arg.Any<long>(), Arg.Any<Expression<Fun<MyClassType, long>>>()); 

// passes, _and_validates first parameter 
myObj.Received(1).DoThing(10, Arg.Any<Expression<Fun<MyClassType, long>>>()); 

// passes, _and_validates first parameter 
myObj.Received(1).DoThing(Arg.Is<long>(10), Arg.Any<Expression<Fun<MyClassType, long>>>()); 
1

是NSubstitute可以處理需要表達式的調用。以下測試通過我:

public class MyClassType { 
    public long Property { get; set; } 
} 
public interface IFoo { 
    void DoThing(int i, Expression<Func<MyClassType, long>> expression); 
} 

[Test] 
public void ReceivedWithAnyExpression() { 
    var myObj = Substitute.For<IFoo>(); 
    myObj.DoThing (10, x => x.Property); 
    myObj.Received(1).DoThing(Arg.Is(10), Arg.Any<Expression<Func<MyClassType, long>>>()); 
} 

什麼是你收到的編譯錯誤?

+0

我的錯誤。這不是一個編譯錯誤(也許我之前有一個錯字)。我正在研究差異。當我縮小到真正的問題時,我會更新我的帖子。 – moswald

+0

你的答案最終幫助我找到正確的答案。謝謝! – moswald