DarioSantarelli.Blog(this);

[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

About these ads

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

  1. immallose said

    Hi,

    Thanks for this…

  2. GatminRK said

    1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: