DarioSantarelli.Blog(this);

Archive for August, 2011

[WPF] Registering the “pack://” scheme in unit tests

Posted by dariosantarelli on August 26, 2011


A while ago I tried to test some WPF resources stored in an assembly (BAML). When I tried to execute the following code in a unit test…

[TestMethod]

public void MyStyle_Should_Be_Loaded()

{           

  ResourceDictionary dictionary = new ResourceDictionary();

  dictionary.Source = new Uri(“pack://application:,,,/TestClassLibrary;component/ResourceDictionary.xaml”,

                              UriKind.RelativeOrAbsolute);

  object style = dictionary[“myStyle”];

 

  Assert.IsNotNull(style);

  Assert.IsTrue(style is Style);

}

… I received the following strange error while trying to instantiate the Uri class…

System.UriFormatException: Invalid URI: Invalid port specified.

But why?
The answer is not so obviuos. That’s because I was executing that code while the pack:// scheme wasn’t yet registered. In fact, this scheme is registered when the Application object is created. The very simple solution is to execute the following code just before executing the test…

[TestInitialize
public void OnTestInitialize() 
{   
   if (!UriParser.IsKnownScheme("pack")) new System.Windows.Application();
} 
 

HTH

Posted in .NET Framework, WPF | 2 Comments »