views:

41

answers:

2

Hi,

I have a a class called "ViewFactory" and this class should deliver the right view

right now it has only one method (and it will grow) which I want to write a unit test against.

the class looks like this...

  public class ViewFactory
{

       [ImportMany(AllowRecomposition=true)]
    IEnumerable<ExportFactory<DependencyObject, IViewMetaData>> Views { get; set; }

    public DependencyObject GetViewByName(string name)
    {
        DependencyObject view = null;

        try
        {
            view = Views.Where(v => v.Metadata.ViewName == name).FirstOrDefault().CreateExport().Value;
            return view;
        }
        catch (Exception ex)
        {

            return view;
        }
    }
}

what I do want is to test my method but don't know how to do it because the List of Views is composed on runtime...

I want to test if I get a view for a valid name and I also want to test if I get null if I have an invalid name

What would be the right way?

+2  A: 

You would provide your ViewFactory with a set of ExportFactory<,> values suitable for the particular test. Different tests might have different sets, to allow you to test different things. Basically you're faking the injected dependency.

Jon Skeet
Thanks for your response. Can you provide some details? Do you mean just to set the list? Or do you mean some mef magic to fake or mock the composition... And if so how? It would be great if you could provide some more details...
silverfighter
@silverfighter See this question for more details on how you might test MEF classes: http://stackoverflow.com/questions/2851140/mef-and-unit-testing-with-nunit
Daniel Plaisted
@silverfighter: I wouldn't use MEF itself to set the list at all... that doesn't sound like something a unit test should be doing. Just set `Views` manually within the unit test, as if you weren't using MEF at all.
Jon Skeet