Moq-ing Dynamics

This post serves as a reminder to myself…largely because I have wasted time tracking this down twice now!

When you are mocking an interface that returns a dynamic object, moq is (as ever) your friend

public interface ISomething {
  dynamic GetSomething();
}

Using the standard moq syntax, you can very easily mock this call to return a real object..

var theThing = new Mock<ISomething>();
  var mockInstance = new SomeMockClass();
  theThing,Setup(t => t.GetSomething()).Returns(mockInstance);

This is a pretty common pattern, but there’s an important gotcha to note: if you the C# runtime binder can’t see the type SomeMockClass then when your target code tries to evaluate the return value you’re going to get an error…

'object' does not something something about GetSomething()

But you aren’t returning an instance of object are you. So why can’t it work out what you’re aiming for?

Turns out that it’s pretty simple. For the dynamic binder to pick up your mock type, it has to be able to see the type. Is your mock type publicly visible? Thought not.

Make your private mock class publicly visible and suddenly the runtime binder knows what you’re talking about!