Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when using Moq.Times with ?: operator

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)
like image 899
THE_GREAT_MARKER Avatar asked Aug 26 '26 13:08

THE_GREAT_MARKER


1 Answers

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());
like image 119
György Kőszeg Avatar answered Aug 28 '26 02:08

György Kőszeg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!