2016-11-16 174 views
0

我是單元測試的新手,聽起來對於我來說應該很容易讓NSubstitute能夠爲方法返回null,但我無法讓它正常工作。NSubstitute返回一個對象爲空

我曾經嘗試這樣做的Get方法應該返回一個活動方法,

_campaigns = Substitute.For<IOptions<Campaigns>>(); 
_campaigns.Get(Arg.Any<string>()).Returns(null); 

在生產中我使用FirstOrDefault()方法返回的運動物體,如果它不存在,它返回null。所以在我的單元測試,我想測試的話,但我不能NSubstitute僞造它,因爲我得到了編譯時下列錯誤:

error CS0121: The call is ambiguous between the following methods or properties: 'SubstituteExtensions.Returns(T, T, params T[])' and 'SubstituteExtensions.Returns(T, Func, params Func[])'

我這樣做是爲了避免錯誤:

_campaigns.Get(Arg.Any<string>()).Returns((Campaign)null); 

但後來我得到在該行執行錯誤:

System.NullReferenceException : Object reference not set to an instance of an object.

+1

第二個例子必須工作,我想。你可以在你得到'NullReferenceException'的地方顯示完整行嗎? - 你明顯使用返回值 – Fabio

回答

0

我發現我使用的是實際的類「廣告系列」,而不是一個接口問題,所以NSubstitute使用的實際類:(

NSubstitute是設計使用接口。

因此,在這種情況下,我沒有使用NSubstitute,而是爲我的課程創建了一個假對象。