表达式引用的方法不属于ISearchIndexClient.Documents.Search方法的模拟对象

问题描述 投票:1回答:1

我正在使用Azure搜索,这是我的单元测试代码:

var expectedResponse = new DocumentSearchResult { };
var _searchIndexRepository = new Mock<ISearchIndexClient>();
_searchIndexRepository
            .Setup(r => r.Documents.Search(It.IsAny<string>(), It.IsAny<SearchParameters>(), It.IsAny<SearchRequestOptions>()))
            .Returns(expectedResponse);

设置时的错误,我得到的是:

表达式引用不属于模拟对象的方法

有没有办法让这个工作?

c# unit-testing azure
1个回答
2
投票

谢谢你的建议。以下解决方法解决了我的问题:

我为SearchIndexClient创建了一个包装器,如下所示:

public interface ICustomSearchIndexClient
{
    DocumentSearchResult<T> Search<T>(string searchTerm, SearchParameters parameters) where T : class;
}

public class CustomSearchIndexClient : ICustomSearchIndexClient
{
    private readonly SearchIndexClient _searchIndexClient;

    public CustomSearchIndexClient(string searchServiceName, string indexName, string apiKey)
    {
        _searchIndexClient = new SearchIndexClient(searchServiceName, indexName, new SearchCredentials(apiKey));
    }

    public DocumentSearchResult<T> Search<T>(string searchTerm, SearchParameters parameters) where T: class
    {
        return _searchIndexClient.Documents.Search<T>(searchTerm, parameters);
    }
}

改变了这样的业务逻辑:

构造函数:

public CustomSearchService(string serviceName, string apiKey, string indexName, ICustomSearchIndexClient customSearchIndexClient)
{
    _serviceName = serviceName;
    _apiKey = apiKey;
    _indexName = indexName;
    _customSearchIndexClient = customSearchIndexClient;
}

搜索方式:

public DocumentSearchResult<CustomSearchResult> Search(string search)
{
    return _customSearchIndexClient.Search<CustomSearchResult>(string.IsNullOrEmpty(search) ? "*" : search, null)
}

像这样改变了我的单元测试:

[TestCategory("UnitTest")]
[TestMethod]
public void SearchTest()
{
    //Arrange
    var expectedResponse = new DocumentSearchResult<Models.CustomSearchResult> {  Count = 1, Results = <instantiate your custom model here>, Facets = < instantiate your custom model here > };

    var searchIndexClient = new Mock<ICustomSearchIndexClient>();
    searchIndexClient.Setup(r => r.Search<Models.CustomSearchResult>(It.IsAny<string>(), null)).Returns(expectedResponse);
    var business = new CustomSearchService("serviceName", "apiKey", "indexname", searchIndexClient.Object);

    //Act
    var result = business.Search("search term");

    //Assert
    Assert.IsNotNull(result, "Business logic method returned NULL");
}

使用ninject将包装器ICustomSearchIndex注入到CustomSearchService业务逻辑中:

Bind<ICustomSearchIndexClient>().To<CustomSearchIndexClient>();
Bind<ICustomSearchService>().To<CustomSearchService>()
    .WithConstructorArgument("serviceName", ConfigurationManager.AppSettings["SearchServiceName"])
    .WithConstructorArgument("apiKey", ConfigurationManager.AppSettings["SearchServiceApiKey"])
    .WithConstructorArgument("indexName", ConfigurationManager.AppSettings["IndexName"]);
© www.soinside.com 2019 - 2024. All rights reserved.