使用moq进行扩展方法的单元测试 [英] Unit Testing for Extension method using moq

查看:389
本文介绍了使用moq进行扩展方法的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为azuresearch的功能uploaddocuments()编写单元测试.

I’m writing a unit test for function uploaddocuments() for azuresearch .

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

不确定为什么它不起作用.

Not sure why it's not working.

代码:

    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);

推荐答案

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

You can't directly mock static method (e.g. extension method) with mocking framework.You can use some wrapper to achieve the same. We can not (by default) mock the static call – it’s a tight coupling that can not be easily broken.

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

Here is a very nice article which shows a way to create a wrapper for static method which can help us in this scenario:

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

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

Alternatively you can use PEX or MOLES for achieving the same result, you can read it further in below doc:

希望有帮助.

这篇关于使用moq进行扩展方法的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆