无法在我的A.CallTo FakeItEasy方法中获取正确的参数

时间:2019-08-23 14:05:25

标签: c# testing nest fakeiteasy

我正在尝试创建一个简单的测试,以检查是否已调用针对Elasticsearch客户端的搜索方法。

public async Task<IReadOnlyCollection<MyClass>> MySearch(string term)
    {
        var searchResponse = _elasticClient.Search<MyClass>(s => s
            .AllIndices()
            .Query(body => body
                .MultiMatch(m => m
                    .Query(term))));

        return searchResponse.Documents;
    }

这是测试:

[Fact]                                                                                           
public async Task MyTest()          
{                                                                                                
    await _searchAgent.MySearch(_term);                                            

    A.CallTo(() => _elasticClient.Search<MyClass(A<ISearchRequest>._))
            .MustHaveHappened();                                                                     
 }                                                                                            

我不太理解这里的错误消息。看起来A.CallTo方法中的参数有问题,但是我认为我忽略了A<ISearchRequest>._的输入?

FakeItEasy.ExpectationException : 

Assertion failed for the following call:

Nest.IElasticClient.Search`1[RiksTV.Api.ContentSearch.Model.ContentSearchTitle](request: <Ignored>)
Expected to find it once or more but didn't find it among the calls:
1: Nest.IElasticClient.Search`1[RiksTV.Api.ContentSearch.Model.ContentSearchTitle](selector: System.Func`2[Nest.SearchDescriptor`1[RiksTV.Api.ContentSearch.Model.ContentSearchTitle],Nest.ISearchRequest])

1 个答案:

答案 0 :(得分:3)

您实际上是在ElasticClient上使用此方法

ISearchResponse<TDocument> Search<TDocument>(
      Func<SearchDescriptor<TDocument>, ISearchRequest> selector = null)
      where TDocument : class

不是

ISearchResponse<TDocument> Search<TDocument>(ISearchRequest request) where TDocument : class;

所以您需要将A.CallTo(..)稍微更改为

A.CallTo(() => elasticClient.Search(A<Func<SearchDescriptor<MyClass>, ISearchRequest>>._))
    .MustHaveHappened();

希望有帮助。