Posts

Showing posts with the label Moq

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(              ...

A Red Herring When Using Moq to Mock Methods With Optional Parameters

I recently spent some time writing unit tests for some code that required me to mock an object that has a method with optional properties. I used the Moq framework, and when I set up the method in question, I defaulted the optional parameters. This was required, as leaving them out of the Setup() call was not allowed. Also as part of my set up of this method, I instructed Moq to return the first parameter as the return value. I've had plenty of experience with Moq and setting up return values for mocked methods, but it didn't prepare me for the mistake I had unknowingly made. Here's how I set the method up originally: _repoMock.Setup(x =>  x.Save( It .IsAny< Click >(),  It .IsAny< string >(),  It .IsAny< bool >(),  It .IsAny< bool >()))     .Returns(( Click  click) => click); When I ran my unit test, the method above resulted in a "Parameter count mismatch" exception. I checked and doub...