c# - 单元测试 - 模拟 - 可覆盖的问题 - 扩展方法

标签 c# azure unit-testing mocking moq

我正在尝试为以下 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
}

我收到以下错误:

Message: System.NotSupportedException : Unsupported expression: ... => ....Index(It.IsAny>(), It.IsAny()) Extension methods (here: DocumentsOperationsExtensions.Index) may not be used in setup / verification expressions.

单元测试代码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
}

我收到以下错误:

Message: System.NullReferenceException : Object reference not set to an instance of an object.
    at Microsoft.Azure.Search.DocumentsOperationsExtensions.IndexAsync[T](IDocumentsOperations operations, IndexBatch^1 batch, SearchRequestOptions searchRequestOptions, CancellationToken cancellationToken)
    at Microsoft.Azure.Search.DocumentsOperationsExtensions.Index[T](IDocumentsOperations operations, IndexBatch^1 batch, SearchRequestOptions searchRequestOptions)

如何测试上传功能?

最佳答案

您基本上是在尝试测试第 3 方依赖项的功能。尽管这些依赖项具有可以模拟的抽象,但它们需要大量不必要的设置来隔离它们以进行单元测试,这对我来说是一种代码味道。

我建议抽象出第三方依赖

private readonly ISearchService service;

//...assuming service injected
public SearchIndexWriter(ISearchService service) {
    this.service = service;
}

public Task Write(ISearchIndexClient indexClient, Search search) {
    return service.UploadContents(indexClient, search.SearchContents);
}

尽量避免与静态问题紧密耦合,因为这会使隔离单元测试变得困难。

服务定义可能如下所示

public interface ISearchService {
    Task UploadContents(ISearchIndexClient indexClient, IReadOnlyCollection<dynamic> searchContents);
}

用一个简单的实现来包装外部依赖项

public class SearchService : ISearchService  {
    private Task UploadContents(ISearchIndexClient indexClient, IReadOnlyCollection<dynamic> searchContents) 
        =>  indexClient.Documents.IndexAsync(IndexBatch.Upload(searchContents));
}

不要因为尝试测试你无法控制的代码而感到压力。相反,请专注于您可以控制的逻辑。

public async Task Write_Success() {
    //Arrange
    var serviceMock = new Mock<ISearchService>();
    serviceMock
        .Setup(_ => _.UploadContents(It.IsAny<ISearchIndexClient>(), It.IsAny<IReadOnlyCollection<It.AnyType>>())
        .ReturnsAsync(new object());

    var searchIndexClientMock = Mock.Of<ISearchIndexClient>();

    var pushFunction = new SearchIndexWriter(serviceMock.Object);

    Search search = new Search();

    //Act
    await pushFunction.Write(searchIndexClientMock.Object, search);

    //Assert, Verify checks
    //...
}

关于c# - 单元测试 - 模拟 - 可覆盖的问题 - 扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58672440/

相关文章:

c# - 如何使用 Entity Framework (EF6) 在 Asp.Net MVC 5 中删除 ApplicationUser?

c# - Kinect 脸部追踪手势

azure - Azure AD 中的 User.ReadWrite 权限

c# - Blob 代码下载速度比 MS Azure Storage Explorer 慢得多

python - 对于unittest.TestCase子类,run方法执行测试用例时无法获取class属性

php - 模拟 HTTP 请求进行单元测试

c# - 如何将非托管对话框设置为 WinForm 窗体的所有者?

c# - 如何在 Prism 6 的 Shell 顶部显示登录模式窗口?

Azure 文件存储 : create share for App Services

ruby-on-rails - Ruby on Rails 单元测试在日期测试中失败