Chung Nguyen
Chung Nguyen

Reputation: 41

How to mock a function which have input is an exception?

I am writing a Unit Test in .netcore C# for a function. In that function, I need to setup a function for mock object. This function have input is an Exception. I try below solution, it compile ok but fail in run-time. Please help.

Need to test function:

    public void MyFunction()
    {
        ...
        try
        {
            ...
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "...");
            ...
        }
    }

In Unit Test , I do setup as below:

_loggerMock.Setup(l => l.LogError(It.IsAny<Exception>(), It.IsAny<string>(), null));

Error when running UT:

System.NotSupportedException: 'Unsupported expression: l => l.LogError(It.IsAny(), It.IsAny(), new[] { }) Extension methods (here: LoggerExtensions.LogError) may not be used in setup / verification expressions.'

Upvotes: 3

Views: 1158

Answers (2)

wenruiLi
wenruiLi

Reputation: 23

The code above not working for me as well. The logger is correctly invoked but verification failed.

Here is the working code for me

_loggerMock.Verify(x => x.Log(It.IsAny<LogLevel>(), It.IsAny<EventId>(), It.IsAny<It.IsAnyType>(), It.IsAny<Exception>(), It.IsAny<Func<It.IsAnyType, Exception?, string>>()),Times.AtLeastOnce);

Try use It.IsAnyType rather than object

https://adamstorr.azurewebsites.net/blog/mocking-ilogger-with-moq

Upvotes: 0

Chung Nguyen
Chung Nguyen

Reputation: 41

I followed the guideline from Simple Ged's comment. And it works now.

Here is the code:

_loggerMock.Setup(x => x.Log(LogLevel.Error, It.IsAny<EventId>(), It.IsAny<object>(), It.IsAny<Exception>(), It.IsAny<Func<object, Exception, string>>()));

Upvotes: 1

Related Questions