我尝试使用 Moq 框架测试我的代码,并且我想验证在某些特殊情况下是否调用了我的方法。为此,我必须使用 Mock.Times。如果我使用 Times likes,它可以正常工作。
MockObject.Verify(x => x.SomeMethod(), Times.Once)
但是因为我有很多方法可以检查我想这样使用它:
System.Func<Times> times = isItCalled ? Times.Once : Times.Never;
MockObject.Verify(x => x.SomeMethod(), times)
为此,我收到以下错误消息:
无法确定条件表达式的类型,因为“方法组”和“方法组”之间没有隐式转换。
这对我来说真的很奇怪,因为我认为这个运算符与以下相同(也可以正常工作):
System.Func<Times> times;
if (isItCalled)
{
times = Times.Once;
}
else
{
times = Times.Never;
}
MockObject.Verify(x => x.SomeMethod(), times)
最佳答案
这是三元运算符的一个已知问题。
一个可能的解决方案:
Func<Times> times = isItCalled ? (Func<Times>)Times.Once : Times.Never;
MockObject.Verify(x => x.SomeMethod(), times);
或者:
// note the parentheses so you pass a Time instance instead of a delegate:
MockObject.Verify(x => x.SomeMethod(), isItCalled ? Times.Once() : Times.Never());
关于c# - 使用 Moq.Times 时出错? : operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61319215/