devlooped / moq

The most popular and friendly mocking framework for .NET
Other
5.94k stars 802 forks source link

NullReferenceException in IMatcher.Matches #1005

Closed eduherminio closed 4 years ago

eduherminio commented 4 years ago

I may have found a bug/issue while using Verify(Expression<Action<T>>, Times, string).

A suspicious NullReferenceException is triggered in Moq.Match.Moq.IMatcher.Matches(Object, Type).

I created a sample repo to easily reproduce this issue.

stakx commented 4 years ago

Seems to me this is your mistake, not a bug inside Moq.

In this line of code:

It.Is<TException>(e => e.GetHashCode() == ex.GetHashCode()),

you haven't considered the possibility that e might be null, so in such cases, e.GetHashCode() will throw a NullReferenceException.

This case appears to be triggered in your failing test:

_service.LogMessage(_level, _level.ToString());   // Logging a simple message
_logger.VerifyLog(_exception, _exception.Message, Times.Once());  // => NullReferenceException

You're logging a message, not an exception.

eduherminio commented 4 years ago

That's it, nice catch! The test was designed like that to trigger the mysterious exception. It.Is<TException>(e => (e != null ? e.GetHashCode() : -1) == ex.GetHashCode()) does the trick