Know your tools

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

Mock<ILookupRegister> _mockLookupRegister;

_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.DynamicProxy.AbstractInvocation.Proceed()
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.


My musing about anything and everything

Posted in Moq, TDD

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 13 other followers
%d bloggers like this: