c# - 使用起订量的扩展方法的单元测试

标签 c# azure unit-testing moq

我正在为 azuresearch 的函数 uploaddocuments() 编写单元测试。

Unsupported expression: ... =>
....Index(It.IsAny<IndexBatch<Document>>(),
It.IsAny<SearchRequestOptions>()) Extension methods (here:
DocumentsOperationsExtensions.Index) may not be used in setup /
verification expressions.

不知道为什么它不起作用。

代码:

    private static async Task uploaddocuments(ISearchIndexClient indexClient)
    {

    var actions = new IndexAction<Hotel>[]
    {

      IndexAction.Upload(
       new Hotel()
       {
           HotelId = "1",
                HotelName = "Secret Point Motel",
                Description = "The hotel is ,

                Rating = 3.6,
                Address = new Address()
                {
                    StreetAddress = "677 5th Ave",
                    City = "New York",
                    StateProvince = "NY",
                    PostalCode = "10022",
                    Country = "USA"
                }

         }
       )
    }
    var batch = IndexBatch.New(actions);
    try
    {
           indexClient.Documents.Index(batch);
    }
    catch (IndexBatchException e)
    {
          console.log(e);
    }
}

测试:

var testMock = new Mock(IDocumentsOperations)();

docOperationsMock.Setup(() => Index(It.IsAny(IndexBatch<Document))(), It.IsAny<SearchRequestOptions)())).Returns(new DocumentIndexResult());


  var mock = new Mock<ISearchIndexClient>()

            .Setup(x => x).Returns(It.IsAny(SearchIndexClient)());

             .SetupGet(a => a.Documents).Returns(It.IsAny("IDocumentsOperations")())

             .Callback(() => IndexBatch.Upload(It.IsAny(IEnumerable(dynamic))()));

            .Returns(testMock.Object);

最佳答案

您不能直接使用模拟框架来模拟静态方法(例如扩展方法)。您可以使用一些包装器来实现相同的目的。 我们不能(默认情况下)模拟静态调用——这是一个紧密的耦合,不容易被打破。

这是一篇非常好的文章,它展示了一种为静态方法创建包装器的方法,这可以在这种情况下帮助我们:

http://adventuresdotnet.blogspot.com/2011/03/mocking-static-methods-for-unit-testing.html

或者,您可以使用 PEX 或 MOLES 来获得相同的结果,您可以在下面的文档中进一步阅读:

https://www.microsoft.com/en-us/research/project/pex-and-moles-isolation-and-white-box-unit-testing-for-net/?from=http%3A%2F%2Fresearch.microsoft.com%2Fen-us%2Fprojects%2Fpex%2Fdownloads.aspx

希望有帮助。

关于c# - 使用起订量的扩展方法的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58671929/

相关文章:

c# - 在表单中调用函数

azure - 是否有一种用户友好的方式来对我的 Azure API 的用户进行身份验证,而无需传递订阅 key 或 token ?

java - 如何确定 Java 中 View 的像素单位(px、dp 等)?

c# - EasyNetQ-如何重试失败的消息并在邮件正文/标题中保留RetryCount?

javascript - 拒绝数字序列的正则表达式,例如 "1234"

azure - 数据 block 中的枢轴问题

c# - 如何向 WebRequest 添加 cookie?

c# - FsCheck 与 C# 中的 NUnit 集成

c# - 这个简单的缓存类需要线程同步吗?

c# - 403 禁止使用 Azure Graph API