How to mock a dynamic object

Someone asked me how to mock a dynamic object with Moq, which might be non-obvious.

Given the following interface definition:

public interface IProject
{
  string Name { get; }
  dynamic Data { get; }
}

When you try to setup the mock for the dynamic property values, you get:

image001

 

What’s important to realize is that a dynamic object is just a plain object, whose properties happen to be resolved at runtime. Kinda like reflection, if you will: all public properties of whatever object happens to be the instance, will be resolved just fine at runtime.

Therefore, one way to mock this dynamic is to just create an anonymous type with the properties we want, and set the dynamic property to return that:...

Read full article

No Comments