I have been using Moq for so long that when I start to write tests, i start writing on automatic and not even think about what I type.
I was busy refactoring some code that I have inherited which of course did not have any units tests. So reviewing the code, I see that got an interface to do a data call
public DataTable GetListLookupDataForCentreByCode(string code, Guid centreId, int periodId, Guid? alwaysIncludeId)
So without even thinking I start writing my mock object
_mockLookupRegister = new Mock<ILookupRegister>();
m => m.GetListLookupDataForCentreByCode(It.IsAny<string>(), It.IsAny<Guid>(), It.IsAny<int>(), It.IsAny<Guid>()))
Run the test expecting it to fail, but I get a unexpected failure message
System.NullReferenceException : Object reference not set to an instance of an object.
at Moq.Match`1.Matches(Object value)
at Moq.MethodCall.Matches(ICallContext call)
at System.Linq.Enumerable.LastOrDefault(IEnumerable`1 source, Func`2 predicate)
at Moq.Interceptor.Intercept(ICallContext invocation)
at Castle.Proxies.ILookupRegisterProxy.GetListLookupDataForCentreByCode(String code, Guid centreId, Int32 academicPeriodId, Nullable`1 alwaysIncludeId)
at Presentation.Pages.Controllers.DataController.GetLookup(Guid centreId, Int32 periodId) in DataController.cs: line 279
at UnitTests.ControllerTests.ForPeriod5.DataControllerTests.LookupTest() in DataControllerTests.cs: line 207
After spending some amount of time trying to work out why Moq was throwing an error that I did not expect, I finally spotted my mistake
The variable alwaysIncludeId was a nullable guid, but I had set up Moq to expect a guid. Hence the failure.
Once quick question mark later and now the test was failing in way that was expected.