A Rather Embarrassing Reason for the "Expression references a method that does not belong to the mocked object" Exception When Using Moq

I've been using Moq for ages, but today while writing a unit test ran into a runtime exception I'd never had before:

Expression references a method that does not belong to the mocked object: mock => mock.GetExpiredCredentials(It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<Boolean>()).Returns<IEnumerable`1>(.fakeResults, new[] {  })

I couldn't understand why. The method in question was on the interface, and if it wasn't, the code shouldn't have even compiled, yet it did. Even more confusing was that, when I Googled the error message, all the results seemed to point toward extension methods, and this method was not an extension method.

It turns out, what I had done was to misplace my parentheses (facepalm)! Here's what my original take looked like:

_credentialServiceMock
    .Setup(mock => 
        mock.GetExpiredCredentials(
            It.IsAny<DateTime>(), 
            It.IsAny<DateTime>(), 
            It.IsAny<bool>())
    .Returns(fakeResults));

And here was the corrected version (notice there's an additional parenthesis at the end of the Setup() call, and one less at the end of the Returns() call...(sigh)...):

_credentialServiceMock
    .Setup(mock => 
        mock.GetExpiredCredentials(
            It.IsAny<DateTime>(), 
            It.IsAny<DateTime>(), 
            It.IsAny<bool>()))
    .Returns(fakeResults);

I've been using Moq for many years, and I can't believe I made this mistake, but hopefully this post will help someone else who's made the same one.

Comments

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

How to Determine if a Column Exists in a DataReader

Silent Renew and the "login_required" Error When Using oidc-client

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4