Ashwin Nair Ashwin Nair - 2 months ago 20
C# Question

C# ternary operator not working

I've got a Moq mock of a class for which I need to verify whether a certain method was called. Depending on the type of a variable, I need to check if the method was called once or never.

So, this works:

if (exception is ValidationException)
mockRequestHandler.Verify(x => x.HandleException(exception),
Times.Once);
else
mockRequestHandler.Verify(x => x.HandleException(exception),
Times.Never);


I'm trying to use a ternary operator as follows, but it doesn't seem to work:

mockRequestHandler.Verify(x => x.HandleException(exception),
(exception is ValidationException) ? Times.Once: Times.Never);


I get the following compile-time error:


Type of conditional expression cannot be determined because there is no implicit conversion between 'method group' and 'method group'.


Is there something simple i'm overlooking or can the ternary operator not be used in this way?

Answer

As I can see in this source file, Times.Once and Times.Never are actually static methods, but not properties.

In order to verify that method is called once or is never called, you need to use it this way:

mockRequestHandler.Verify(x => x.HandleException(exception), Times.Once());
mockRequestHandler.Verify(x => x.HandleException(exception), Times.Never());

So, using a ternary operator it will be:

mockRequestHandler.Verify(x => x.HandleException(exception), 
    (exception is ValidationException) ? Times.Once() : Times.Never());