Pack Urls and Unit Testing. Problem with my environment? Pack Urls and Unit Testing. Problem with my environment? wpf wpf

Pack Urls and Unit Testing. Problem with my environment?


I got bitten by this problem once too...

Referencing the assemblies isn't enough. WPF needs to call System.UriParser.Register() with its own URI parser so that System.Uri can interpret pack URLs.

Reflecting tells us that this is done by the static constructor of System.IO.Packaging.PackUriHelper. Call any method of this class in your test, like PackUriHelper.Create() to ensure the URI parser is well registered. Kind of ugly, but should work.


Building on other answers, here's the (NUnit) code that made my tests go green:

In AssemblyInfo.cs:

[assembly: RequiresSTA]

In its own file:

[SetUpFixture]public class PreTestSetup{    [SetUp]    public void Setup()    {        PackUriHelper.Create(new Uri("reliable://0"));        new FrameworkElement();        System.Windows.Application.ResourceAssembly = typeof (App).Assembly;    }}

App is my main application class. Any class in the relevant assembly will do, presumably.


A small code sample to add to the answers above. We use the following in a unit test to get around this issue.

    [AssemblyInitialize]    public static void MagicHappensHere(TestContext context) {        PackUriHelper.Create(new Uri("reliable://0"));    }

Once this has been called at the test startup it all works perfectly.