2014-07-10 43 views
2

我需要模擬對象中方法的返回值。我有這樣的事情:使用Mock.of對象的Moq返回值?

var mock = Mock.Of<IExample>(x => x.GetAll() == new List<IOtherExample>()) ; 

但我得到一個錯誤。如果我使用GETALL的屬性,而不是它的工作原理:

var mock = Mock.Of<IExample>(x => x.GetAll == new List<IOtherExample>()) ; 

我知道我能做到這一點使用新的模擬,設置並返回這樣的:

mock.Setup(x => x.GetAll()).Returns(new List<IOtherExample>()); 

,但我想了解如何做到這一點使用Mock.Of.

錯誤看起來是這樣的:

Expression of type 'System.Collections.Generic.List' cannot be used for parameter of type 'System.Collections.Generic.IList' of method 'Moq.Language.Flow.IReturnsResult' Returns(System.Collections.Generic.IList)' 

再次記住,它的工作原理,如果GETALL是一個屬性。

謝謝。

public interface IExample : IGenericExample<IOtherExample> 
{ 

} 

public interface IGenericExample<T> 
{ 
    IList<T> GetAll() 
} 
+0

也許如果你粘貼了一個完整的代碼示例會有所幫助,那麼試試LINQPad中一個簡單但類似的東西對我來說很合適。我想'x = ...'是一個錯字,因爲它應該是'x => ...'。 – PermaFrost

+0

我添加了接口的外觀。除此之外,沒有更多的代碼似乎相關。我修正了你提到的錯字。 LINQ表達式在編譯時是有效的。它在運行時失敗。 – d0001

回答

2

無法發佈此作爲註釋由於代碼格式化:

void Main() 
{ 
    var t = Mock.Of<IExample>(x => x.GetAll() == new List<IOtherExample>()); 
    t.GetAll().Dump(); 
} 

// Define other methods and classes here 
public interface IOtherExample 
{ 
} 

public interface IExample : IGenericExample<IOtherExample> 
{ 

} 

public interface IGenericExample<T> 
{ 
    IList<T> GetAll(); 
} 

這工作在我的LINQPad,我使用起訂量4.0。我錯過了什麼嗎?