模拟一个采用默认为 null 的可选参数的方法

Mocking out a method that takes optional parameters that default to null

我正在针对通过 NEST 命中 Elasticsearch 的函数编写单元测试。我的单元测试设置如下所示:

var mockResponse = new Mock<IBulkResponse>();
var mockClient = new Mock<IElasticClient>();
mockClient.Setup(x => x.IndexManyAsync<Store>(It.IsAny<IEnumerable<Store>>(), It.IsAny<string>(), It.IsAny<string>())).Returns(Task<IBulkResponse>.Run(() => mockResponse.Object));

IndexManyAsync 函数的函数签名为 Task<IBulkResponse> IndexManyAsync<T>(IEnumerable<T> object, string index = null, string type = null)

如您所见,我尝试设置我的模拟 IElasticClient 来模拟上面的那个方法,但我得到以下异常:

An exception of type 'System.NotSupportedException' occurred in Moq.dll but was not handled in user code

Additional information: Expression references a method that does not belong to the mocked object: x => x.IndexManyAsync<Store>(It.IsAny<IEnumerable`1>(), It.IsAny<String>(), It.IsAny<String>())

我不清楚这里发生了什么。为什么我无法模拟这个采用可选参数的方法?

看来 IndexManyAsync is an extension method:

的这个特殊重载
public static Task<IBulkResponse> IndexManyAsync<T>(this IElasticClient client, 
                                                    IEnumerable<T> objects, 
                                                    string index = null, 
                                                    string type = null) where T : class
{
    // <snip>
}

You cannot use Moq to mock extension methods.