I try to test my code using Moq framework, and I would like to verify if my methods are called or not in some special cases. For this I have to use Mock.Times. If I use Times likes this it works properly.
MockObject.Verify(x => x.SomeMethod(), Times.Once)
But because I have many methods to check I want to use it this way:
System.Func<Times> times = isItCalled ? Times.Once : Times.Never;
MockObject.Verify(x => x.SomeMethod(), times)
And for this I get the following error message: Type of conditional expression cannot be determined because there is no implicit conversion between 'method group' and 'method group'.
That is really weird for me, because I thought this operator is same as the following (which also work properly):
System.Func<Times> times;
if (isItCalled)
{
times = Times.Once;
}
else
{
times = Times.Never;
}
MockObject.Verify(x => x.SomeMethod(), times)
This is a known issue with the ternary operator.
A possible solution:
Func<Times> times = isItCalled ? (Func<Times>)Times.Once : Times.Never;
MockObject.Verify(x => x.SomeMethod(), times);
Or:
// note the parentheses so you pass a Time instance instead of a delegate:
MockObject.Verify(x => x.SomeMethod(), isItCalled ? Times.Once() : Times.Never());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With