Gilad
Gilad

Reputation: 6575

ResourceDictionay in unit testing WPF

I'm using a base class for dynamically created plugins which are in MVVM style I have this function which I want to call in order to get the view

public override System.Windows.ResourceDictionary GetViewTemplate()
{
    var dictionary = new ResourceDictionary
    {
        Source = new Uri("/IPDev.Plugins.Calibration.Comment;component/CommentCmcTemplate.xaml",
                       UriKind.RelativeOrAbsolute)
    };
    return dictionary;
}

this is the function which is calling my function

public CalibrationViewModelBase Load(ProductionProjectVersions productionProjectVersions, IAdditionalDataStorageService additionalDataservice, CalibrationToolVersion calibrationToolVersion) 
{
    var viewModel = GetViewModel(productionProjectVersions, calibrationToolVersion);
    viewModel.Title = GetTitle();            
    viewModel.AdditionalDataService = additionalDataservice;
    viewModel.ConverterFactory = GetConverterFactory(productionProjectVersions);
    ResourceDictionary dict = GetViewTemplate(); //here is the call
    Application.Current.Resources.MergedDictionaries.Add(dict);
    viewModel.HelpTemplate = dict[HELP_TEMPLATE_NAME] as DataTemplate;            
    return viewModel;
}

in the unit test of course the view doesn't exist. Can you suggest of a way to overcome this problem?

Upvotes: 2

Views: 349

Answers (1)

ibebbs
ibebbs

Reputation: 1993

Extract your GetViewTemplate method into an external dependency that can be mocked. For example, create a new ViewTemplateRepository class and associated IViewTemplateRepository interface which has the GetViewTemplate method.

In your runtime code, inject a ViewTemplateRepository class instance into the calling class. In your test code, inject a mock of IViewTemplateRepository into the calling class and mock the GetViewTemplate method to return the appropriate resource dictionary.

Upvotes: 1

Related Questions