You are surely, as I am, creating a lot of units tests in your WPF applications.

Some of the tests may use statics or dynamics resources declared in your application and when you launch the tests, all you get is an XamlParseException exception thrown.

System.Windows.Markup.XamlParseException: 'Provide value on 'System.Windows.StaticResourceExtension' threw an exception.' Line number '11' and line position '83'.
---> System.Exception: Cannot find resource named 'myStaticResource'. Resource names are case sensitive.



The tip to make them work is quite simple to use. What is actually happening ? : the created control is looking for the resource via the classic russian puppets system and does not find the application because the tests does not create it. And the application is exactly where you have declared the needed ressources. So all we've got to do is to create the application and initialize it before running the tests.

Also we called the InitializeComponent() methods to make sure the application is initialized. It seems that this last part is only necessary if the resources are from the same assembly than the application.

So just add this method to your tests classes :

/// <summary>
///Use ClassInitialize to run code before running the first test in the class
/// </summary>
/// <param name="testContext">The test context.</param>
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
  //Create the application for resources.
  if (System.Windows.Application.Current == null)
  {
    App application = new App();
    application.InitializeComponent();
  }
}



The App.xaml content is below:

<Application x:Class="MyAssembly.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:myLib="clr-namespace:MyAssembly.ViewModels"
	StartupUri="Views\MainWindow.xaml">
 
  <Application.Resources>
    <ResourceDictionary>
      <myLib:ViewModelLocator x:Key="myStaticResource" />
    </ResourceDictionary>
 
  </Application.Resources>
</Application>

Here we are !


Shout it kick it on DotNetKicks.com