scourge192
scourge192

Reputation: 2139

Use ItExpr.IsNull<TValue> rather than a null argument value, as it prevents proper method lookup

I am trying to write a unit test where I need to set up a protected method. I am using Moq for this setup.

_innerHandler.Protected()
             .Setup<Task<HttpResponseMessage>>("SendAsync", It.IsAny<HttpRequestMessage>(), It.IsAny<CancellationToken>())
             .ReturnsAsync(responseMessage);

When this line executes, it throws the following exception:

System.ArgumentException : Use ItExpr.IsNull<TValue> rather than a null argument value, as it prevents proper method lookup.

When I change it to use ItExpr.IsNull<TValue>, it does allow the test to execute. However, it is of course missing the setup I wanted to configure.

What do I need to do in order to set up a protected method using It.IsAny<TValue>?

Upvotes: 54

Views: 8749

Answers (1)

scourge192
scourge192

Reputation: 2139

When setting up an IProtectedMock, you should use Moq.Protected.ItExpr instead of Moq.It.

Here is the corrected implementation of what I was trying to do in my question:

_innerHandler.Protected()
             .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
             .ReturnsAsync(responseMessage);

Upvotes: 93

Related Questions