【问题标题】:Error when using Moq.Times with ?: operator将 Moq.Times 与 ?: 运算符一起使用时出错
【发布时间】:2020-04-20 09:32:44
【问题描述】:

我尝试使用 Moq 框架测试我的代码,并且我想验证在某些特殊情况下是否调用了我的方法。为此,我必须使用 Mock.Times。如果我使用 Times like this,它可以正常工作。

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)

【问题讨论】:

  • 你可以试试这个:System.Func&lt;Times&gt; times = isItCalled ? ((System.Func&lt;Times&gt;)Times.Once) : Times.Never;
  • 非常感谢!!有用!但是你能解释一下为什么这种显式转换是必要的吗?

标签: c# mocking operators


【解决方案1】:

这是三元运算符的一个已知问题。

一个可能的解决方案:

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

【讨论】:

    猜你喜欢
    • 2012-10-15
    • 2011-04-12
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2020-04-22
    • 2017-11-17
    • 2013-09-10
    相关资源
    最近更新 更多