Setup Method With Params Array

前端 未结 3 1439
悲哀的现实
悲哀的现实 2020-12-06 08:57

I am developing tests for an application. There\'s a method that has a params array as a parameter. I have set up the method using Moq but when I run the test,

相关标签:
3条回答
  • 2020-12-06 09:25

    I believe the params string has to be matched by It.IsAny<string[]>() rather than It.IsAny<string>()

    0 讨论(0)
  • 2020-12-06 09:38

    You're trying to call a method taking a single string, rather than an array. Bear in mind that it's the C# compiler which handles the params part, converting calling code which just specifies individual values into a call passing in an array. As far as the method itself is concerned, it's just getting an array - and that's what you're mocking.

    The compiler is actually turning your code into:

    mock.Setup(m => m.GetFirstTicketInQueueIfMatches
                            (new string[] { It.IsAny<string>() }))
    

    which isn't what you want.

    You should use:

    mock.Setup(m => m.GetFirstTicketInQueueIfMatches(It.IsAny<string[]>()))
    

    If you need to verify that it only gets given a single value, you'll need to do that in the same way you would for a non-params parameter.

    Basically, params only makes a difference to the C# compiler - not to moq.

    0 讨论(0)
  • 2020-12-06 09:47

    Using Moq, the code below works to setup a callback on a method with a params argument. Defining the second argument as an array does the trick.

            MockLogger
                .Setup(x => x.Info(It.IsAny<string>(), It.IsAny<object[]>()))
                .Callback<string, object[]>((x, y) => _length = x.Length);
    
    0 讨论(0)
提交回复
热议问题