当使用Moq.Times时出错,并带有?

问题描述 投票:2回答:1

我试图使用Moq框架来测试我的代码,我想验证我的方法在一些特殊情况下是否被调用。为此,我必须使用Mock.Times。如果我使用Times这样,它就能正常工作。

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)
c# mocking operators
1个回答
2
投票

这是一个已知的三元操作符的问题。

一个可能的解决方案。

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());
© www.soinside.com 2019 - 2024. All rights reserved.