我正在为azuresearch的功能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);
答案 0 :(得分:1)
您不能使用模拟框架直接模拟静态方法(例如扩展方法),可以使用一些包装器来实现相同的目的。 我们无法(默认情况下)模拟静态调用-这是紧密耦合,不能轻易破坏。
这是一篇非常不错的文章,展示了一种为静态方法创建包装的方法,该方法可以在这种情况下为我们提供帮助:
http://adventuresdotnet.blogspot.com/2011/03/mocking-static-methods-for-unit-testing.html
或者,您可以使用PEX或MOLES获得相同的结果,您可以在下面的文档中进一步阅读:
希望有帮助。