Firoso
Firoso

Reputation: 6685

How can a class be designed to mock an unknown type?

I've seen examples of this where an interface is provided to a factory and it generates objects that implement the interface. This isn't that complicated to me, but what I don't get is how that can be used to implement behavior.

Take for example the ChannelFactory in WCF... when you generate a channel from an interface it exposes methods (from the interface) that when invoked call remote procedures. I seem to have a small gap in my knowledge on how this can be done. It's probably a common design pattern but I figured I'd use SO as a research extension once again.

Upvotes: 3

Views: 672

Answers (2)

user438034
user438034

Reputation:

Usually happens through code emission. See the classes in System.Reflection.Emit.

For example, you could get an interface Type and go over the methods it declares, then build your own type which inherits it, using TypeBuilder, and implement whatever functionality you desire in the methods (or just them make empty / do a return default(T)), using MethodBuilder, and so on, until you've satisfied the interface.

Upvotes: 1

Dave Swersky
Dave Swersky

Reputation: 34810

Mocking frameworks that mock an interface generate a dynamic class that implements the interface. The behavior of the mocked method(s) will depend on the framework. Generally, the method will do nothing unless an implementation is provided through the mock.

For example:

Mock<IRepository> repMock = new Mock<IRepository>();
repMock.Setup(r => r.FindById(1)).Returns(new MyObject());

Assuming the IRepository interface defines a FindByID method, the Setup method of the mock dynamically generates an implementation of the method and "injects" it into the mock. This is done using Reflection.Emit, which can be used to dynamically build IL instructions and compile them on the fly.

Upvotes: 1

Related Questions