问题
I’m writing a unit test for function uploaddocuments() for azuresearch .
Unsupported expression: ... => ....Index(It.IsAny<IndexBatch<Document>>(), It.IsAny<SearchRequestOptions>()) Extension methods (here: DocumentsOperationsExtensions.Index) may not be used in setup / verification expressions.
Not sure why it's not working.
code:
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);
}
}
Test:
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);
回答1:
You can't directly mock static method (e.g. extension method) with mocking framework.You can use some wrapper to achieve the same. We can not (by default) mock the static call – it’s a tight coupling that can not be easily broken.
Here is a very nice article which shows a way to create a wrapper for static method which can help us in this scenario:
http://adventuresdotnet.blogspot.com/2011/03/mocking-static-methods-for-unit-testing.html
Alternatively you can use PEX or MOLES for achieving the same result, you can read it further in below doc:
https://www.microsoft.com/en-us/research/project/pex-and-moles-isolation-and-white-box-unit-testing-for-net/?from=http%3A%2F%2Fresearch.microsoft.com%2Fen-us%2Fprojects%2Fpex%2Fdownloads.aspx
Hope it helps.
来源:https://stackoverflow.com/questions/58671929/unit-testing-for-extension-method-using-moq