模拟一个接受默认为null的可选参数的方法

本文关键字:null 方法 参数 默认 一个 模拟 | 更新日期: 2023-09-27 18:02:31

我正在编写一个针对通过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)函数签名。

正如您所看到的,我试图设置我的mock 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>())

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

模拟一个接受默认为null的可选参数的方法

看来IndexManyAsync的这个特殊重载是一个扩展方法:

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

你不能使用Moq来模拟扩展方法