views:

299

answers:

1

With reference to the Managed Extensibility Framework (MEF), I'm trying to work out how to create clean tests with mocks.

I have an exported component which has three private imports. Each imported object (field) needs to be mocked. Given that the CompositionContainer uses fancy reflection tactics to set imported private fields of composable parts, even in unit tests I will need to use the container to set those field values.

How do I tell the container at run time to accept a dynamic object I've created with Rhino Mocks as a valid export so that it can be used to satisfy the imports in the component I'm testing?

+1  A: 

My question has been answered here.


Hi Nathan

There's a couple of different options here.

  1. Using a batch, you can call the AddExportedObject method to add a mock instance to the container. AddExportedObject allows you to specify the contract for the instance that you are adding. i.e. batch.AddExportedObject(mockLogger, typeof(ILogger));

  2. You an also create a custom export provider to allow you add mock instances. If you follow this link, here are some utils that I use. http://pastie.org/467842. Within you'll find a FakeExportProvider, along with FakeExportDefinitions. The FakeExportDefinitions take a func for the instance. This means you can pass it an instance, or even directly create a mock.

Here's sample code to illustrate usage.

    protected override void Context()
    {
        MockCache = MockRepository.GenerateStub<ICache>();
        var metadata = new Dictionary<string, object> ()
        var cacheDefinition = new FakeInstanceExportDefinition(typeof(ICache), MockCache, metadata);
        FakeProvider = new FakeExportProvider(f => ((FakeInstanceExportDefinition)f).Instance);
        FakeProvider.AddExportDefinitions(cacheDefinition);
        CacheExport = FakeProvider.GetExport<ICache>();
    }

Now above I am querying the export provider directly. However, our container allows passing in an export provider in it's construction. So you can do this...

var container = new CompositionContainer(null, FakeProvider).

HTH Glenn

Nathan Ridley