【问题标题】:Why am I getting InvalidComObjectException after creating a WPF window in a NUnit test?为什么在 NUnit 测试中创建 WPF 窗口后会出现 InvalidComObjectException?
【发布时间】:2013-09-20 21:57:52
【问题描述】:

我还没有为 NUnit 解决这个问题。有一个类似的问题,here 提出了这个异常。答案解决了 xUnit 的使用问题,提问者报告说他让它为 MSTest 工作。我尝试在[TearDown][TestFixtureTearDown][Test] 方法中调用Dispatcher.CurrentDispatcher.InvokeShutdown();,但仍然出现异常。

关于我的实现的更多细节:我创建了一个扩展 System.Windows.Window 的 InputBox 类。我做了一个静态方法,InputBox.Show(prompt),它执行以下代码:

        var input = "";
        var t = new Thread(() =>
            {
                var inputBox = new InputBox(prompt);
                inputBox.ShowDialog();
                input = inputBox.Input;
            }) {IsBackground = true};
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
        t.Join();
        return input;

有什么想法吗?

【问题讨论】:

  • 我在您的代码中没有看到任何 Dispatcher。添加Dispatcher.Run() 作为线程的最后一行。
  • 代码 sn-p 不是很有帮助,它实际上并没有显示对 InvokeShutdown 的调用。 WPF 对线程非常挑剔。此代码完成后,STA 线程是一只死去的挪威鹦鹉。不要试图阻止它,它正停在笼子的底部,渴望峡湾。 NUnit 确实使将测试线程配置为 STA 线程变得更加困难。被this answer覆盖

标签: c# wpf nunit


【解决方案1】:

感谢 cmets 中关于 Dispatcher 调用的想法。我更改了 InputBox.Show 方法,现在看起来像这样,而且效果很好。我的单元测试中没有任何 Dispatcher 调用,也没有出现异常。

    public static string Show(string prompt)
    {
        string input = null;
        var t = new Thread(() =>
        {
            Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
            {
                var inputBox = new InputBox(prompt);
                inputBox.ShowDialog();
                input = inputBox.Input;
            }));
            Dispatcher.CurrentDispatcher.InvokeShutdown();
        }) { IsBackground = true };
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
        t.Join();
        return input;
    }

【讨论】:

  • 在运行进度条(在它自己的窗口中)然后打开第二个窗口时遇到了这个问题。谢谢。
【解决方案2】:

您是否在您的测试方法之上尝试过 [RequireMTA](使用智能来证明正确性)属性? ApartmentState.STA - 在我看来是给你带来麻烦的声明

【讨论】:

  • 线程必须是 STA 才能创建窗口。 WPF 需要 STA 用于 GUI 组件。
猜你喜欢
  • 2013-06-16
  • 2014-05-27
  • 1970-01-01
  • 2022-12-11
  • 1970-01-01
  • 2014-09-09
  • 2011-08-16
  • 2014-05-25
  • 2011-09-04
相关资源
最近更新 更多