[英]Unit Testing for Extension method using moq
我正在為 azuresearch 編寫 function uploaddocuments() 的單元測試。
Unsupported expression: ... =>....Index(It.IsAny<IndexBatch<Document>>(), It.IsAny<SearchRequestOptions>()) Extension methods (here: DocumentsOperationsExtensions.Index) may not be used in setup / verification expressions.
不知道為什么它不起作用。
代碼:
private static async Task uploaddocuments(ISearchIndexClient indexClient)
{
var actions = new IndexAction<Hotel>[]
{
IndexAction.Upload(
new Hotel()
{
HotelId = "1",
HotelName = "Secret Point Motel",
Description = "The hotel is ,
Rating = 3.6,
Address = new Address()
{
StreetAddress = "677 5th Ave",
City = "New York",
StateProvince = "NY",
PostalCode = "10022",
Country = "USA"
}
}
)
}
var batch = IndexBatch.New(actions);
try
{
indexClient.Documents.Index(batch);
}
catch (IndexBatchException e)
{
console.log(e);
}
}
測試:
var testMock = new Mock(IDocumentsOperations)();
docOperationsMock.Setup(() => Index(It.IsAny(IndexBatch<Document))(), It.IsAny<SearchRequestOptions)())).Returns(new DocumentIndexResult());
var mock = new Mock<ISearchIndexClient>()
.Setup(x => x).Returns(It.IsAny(SearchIndexClient)());
.SetupGet(a => a.Documents).Returns(It.IsAny("IDocumentsOperations")())
.Callback(() => IndexBatch.Upload(It.IsAny(IEnumerable(dynamic))()));
.Returns(testMock.Object);
您不能使用 mocking 框架直接模擬 static 方法(例如擴展方法)。您可以使用一些包裝器來實現相同的目的。 我們不能(默認情況下)模擬 static 調用——這是一個不能輕易破壞的緊密耦合。
這是一篇非常好的文章,它展示了一種為 static 方法創建包裝器的方法,它可以在這種情況下幫助我們:
http://adventuresdotnet.blogspot.com/2011/03/mocking-static-methods-for-unit-testing.html
或者,您可以使用 PEX 或 MOLES 來獲得相同的結果,您可以在下面的文檔中進一步閱讀:
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.