设置方法使用参数数组 [英] Setup Method With Params Array
问题描述
我开发一个应用程序的测试。还有,有一个 PARAMS
数组作为参数的方法。我已成立的方法,使用起订量,但是当我运行测试,该方法的返回值是零,这意味着它不被嘲笑。
下面是一个代码示例:
公共接口ITicketManager {
串GetFirstTicketInQueueIfMatches(PARAMS字符串[] ticketsToMatch);
}
公共类TicketManager:ITicketManager {
专用队列<串GT; ticketQueue =新队列<串GT;();
公共字符串GetFirstTicketInQueueIfMatches(PARAMS字符串[] ticketsToMatch){
VAR firstQueuedTicket = ticketQueue.Peek();
VAR firstQueuedTicketMatchesAnyOfRequested = ticketsToMatch.Any(T =>吨== firstQueuedTicket);
如果(firstQueuedTicketMatchesAnyOfRequested)
返回firstQueuedTicket;
返回NULL;
}
}
中的模拟代码如下所示:
VAR模拟=新模拟< ITicketManager>();
mock.Setup(M = GT; m.GetFirstTicketInQueueIfMatches(It.IsAny<串GT;()))
.Returns(P => {
如果(第包含(A))
返回A;
返回NULL;
});
为什么它从来没有碰到嘲笑的方法?
您正在试图调用采取一个字符串,而不是一个数组的方法。请记住,这是C#编译器它处理 PARAMS
部分,转换调用代码刚刚指定单独的值传递到阵列中的一个电话。至于方法本身而言,它只是得到一个数组 - 这就是你在嘲笑什么
编译器是的真正的转弯你的代码到:
mock.Setup(M = GT; m.GetFirstTicketInQueueIfMatches
(新的String [] {它.IsAny<串>()}))
这是不是你想要的。
您应该使用:
mock.Setup(M = GT,M。 GetFirstTicketInQueueIfMatches(It.IsAny<字符串[]>()))
如果您需要验证它只是被赋予一个值,你需要做的,在你会为一个非PARAMS参数相同的方式。
基本上, PARAMS
只能在本C#编译器的差异 - 不是起订量
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, the return value of the method is null, which means it is not being mocked.
Here's a code sample:
public interface ITicketManager {
string GetFirstTicketInQueueIfMatches(params string[] ticketsToMatch);
}
public class TicketManager : ITicketManager {
private Queue<string> ticketQueue = new Queue<string>();
public string GetFirstTicketInQueueIfMatches(params string[] ticketsToMatch) {
var firstQueuedTicket = ticketQueue.Peek();
var firstQueuedTicketMatchesAnyOfRequested = ticketsToMatch.Any(t => t == firstQueuedTicket);
if(firstQueuedTicketMatchesAnyOfRequested)
return firstQueuedTicket;
return null;
}
}
The mock code looks like this:
var mock = new Mock<ITicketManager>();
mock.Setup(m => m.GetFirstTicketInQueueIfMatches(It.IsAny<string>()))
.Returns(p => {
if(p.Contains("A"))
return "A";
return null;
});
Why it never hits the mocked method?
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
.
这篇关于设置方法使用参数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!