Pack Urls and Unit Testing. Problem with my environment?

后端 未结 4 974
陌清茗
陌清茗 2021-02-07 04:45

So I\'ve got this nice little MVVM solution, and things work great. I\'ve got a view model for a header bar that adjusts the icon based on the state of the application, etc. I\'

相关标签:
4条回答
  • 2021-02-07 04:52

    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.

    0 讨论(0)
  • 2021-02-07 04:57

    I think you can fix this by creating an instance of your main application class before running any tests. This will wire up the handlers that Julien mentions in the other answer.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-07 05:12

    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.

    0 讨论(0)
提交回复
热议问题