简体   繁体   中英

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?

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM