Search code examples
c#mef

Unit tests with MEF2 ExportFactories


We have just recently switched to using .Net4.5 and I am doing some refactoring to take advantage of the new ExportFactories.

My question is how do I mock these for unit testing as I inject them into my constructor, but I'm not 100% sure on the best approach to these from a unit testing standpoint.


Solution

  • The constructor of ExportFactory takes a function that returns a tuple containing the export and another function that release the export. So you can do something like that:

    static Tuple<ISomething, Action> CreateMock()
    {        
        return new Tuple<ISomething, Action>(new MockSomething(), 
                                             () => Console.WriteLine("Releasing..."));
    }
    

    and inject it to your other class' constructor with something like:

    var obj = new OtherClass(new ExportFactory<ISomething>(CreateMock));