tags:

views:

258

answers:

2

I would like to find a way to have a Dictionary of various Mock objects with their various instances keyed by some kind of unique identifier. I am using Moq, so the syntax for that is Mock<IFoo> as far as the typing goes. But I would like to have the Dictionary contain basically this so I can dynamically resolve and overwrite instances at runtime:

Key = IFoo (basically a type)

Value = new SomeCustomType< T >
{
  T ConcreteObject
  Mock< T > MockObject
}

I may not be getting my question across appropriately but I could use some help!

+1  A: 

I'm not 100% sure I understand the question, but here's my take. If you want a dictionary of instances keyed by type, the easiest way to do that is to use a static generic class rather than an actual dictionary:

public static class Dict<T> {
    public static T Instance { get; set; }
}

Then, to set the instance associated with type IFoo you would do Dict<IFoo>.Instance = myIFooInstance;, and to get it back out you'd just store the result of Dict<IFoo>.Instance.

If instead, you want to get out Mock instances keyed by types, you could do something very similar:

public static class MockDict<T> {
    public static Mock<T> Instance { get; set; }
}

Then, you can do something along the lines of:

Mock<IFoo> myMock = ...
MockDict<IFoo>.Instance = myMock;
...
Mock<IFoo> myMock2 = MockDict<IFoo>.Instance;
kvb
+1  A: 

If you don't need the concrete object you could use an automocking container.

Here's an Autofac automocking container for Moq.

Mauricio Scheffer