【发布时间】:2019-11-02 15:21:58
【问题描述】:
我正在尝试为以下 Azure 搜索方法编写单元测试:
public async Task Write(ISearchIndexClient indexClient, Search search)
{
await UploadContents(indexClient, search.SearchContents);
}
private static async Task UploadContents(ISearchIndexClient indexClient, IReadOnlyCollection<dynamic> searchContents) => await Task.Run(() => indexClient.Documents.Index(IndexBatch.Upload(searchContents)));
单元测试代码 1:
public async Task Write_Success()
{
var searchIndexClientMock = new Mock<ISearchIndexClient>();
searchIndexClientMock
.Setup(x => x.Documents.Index(It.IsAny<IndexBatch<Document>>(), It.IsAny<SearchRequestOptions>()))
.Returns(It.IsAny<DocumentIndexResult>()).Callback(() => IndexBatch.Upload(It.IsAny<IEnumerable<Document>>()));
var pushFunction = new SearchIndexWriter();
Search search = new Search();
await pushFunction.Write(searchIndexClientMock.Object, search);
//Assert, Verify checks
}
我收到以下错误:
消息:System.NotSupportedException:不支持的表达式:... => ....Index(It.IsAny>(), It.IsAny()) 扩展方法(此处:DocumentsOperationsExtensions.Index)不能用于设置/验证表达式。
单元测试代码 2:
public async Task Write_Success()
{
var searchIndexClientMock = new Mock<ISearchIndexClient>();
searchIndexClientMock
.SetupGet(x => x.Documents).Returns(It.IsAny<IDocumentsOperations>());
var pushFunction = new SearchIndexWriter();
var search = new Search()
{
SearchContents = new List<dynamic>(),
};
await pushFunction.Write(searchIndexClientMock.Object, search);
//Verify, Assert logic
}
我收到以下错误:
消息:System.NullReferenceException:对象引用未设置为对象的实例。
在 Microsoft.Azure.Search.DocumentsOperationsExtensions.IndexAsync[T](IDocumentsOperations 操作,IndexBatch^1 批处理,SearchRequestOptions searchRequestOptions,CancellationToken cancelToken)
在 Microsoft.Azure.Search.DocumentsOperationsExtensions.Index[T](IDocumentsOperations 操作,IndexBatch^1 批处理,SearchRequestOptions searchRequestOptions)
如何测试上传功能?
【问题讨论】:
标签: c# azure unit-testing mocking moq