Daniel Cazzulino's Blog

Go Back to
kzu′s Latest post

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:



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:

var data = new
    AssemblyName = "Something.dll",
    DefaultNamespace = "Something",
var item = Mock.Of<IProject>(i => i.Name == "Bar" &&
                                  i.Data == data);

Note that I’m also using the linq to mocks syntax which makes for much more concise and “declarative” way of specifying stub behaviors. That syntax doesn’t work for dynamic properties though, unfortunately Sad smile, and you’d get the same compile error as before.

The equivalent imperative style would be:

var item = new Mock<IProject>();
item.Setup(i => i.Name).Returns("Bar");
item.Setup(i => i.Data).Returns(data);

I hardly use that syntax anymore (except for dynamics). It gets really annoying for setting multiple properties and method return values…


Happy moqing!



  1. Thanks for writing this article, Daniel, as this was just what I was looking for!

  2. [...] How to mock a dynamic object – Daniel Cazzulino takes a look at mocking a dynamic object using the Moq framework, showing how, due to dynamic’s nature you can actually use an anonymous type as the payload for the dynamic object. [...]