c# - 使用 Moq.Times 时出错? : operator

标签 c# mocking operators

我尝试使用 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/

相关文章:

C#赋值题

c# - 如何在 web.config 文件中创建 <location> 标签?

c# - 这会工作 MVVM 模式吗?

c# - 我可以使用 FakeItEasy 伪造 Properties.Settings.Default 属性吗?

model-view-controller - 我应该测试我的 Controller (MVC)吗?

r - 最快的 R 实现

c# - 当从 c# 调用外部 dll 时,空格从命令行参数中删除

c# - 当数字是整数而不是小数或 double 时,为什么 WriteLine 会跳过 Tab

typescript - 如何在 Jest 中模拟一个函数

C++赋值运算符,我们可以用copy来代替它吗?