我正在使用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);
设置时的错误,我得到的是:
表达式引用不属于模拟对象的方法
有没有办法让这个工作?
答案 0 :(得分: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"]);