c# - 从测试运行 WPF 对话框

标签 c# wpf xunit.net modern-ui

当我从单元测试中运行 ShowDialog 调用时,我得到了一个

System.Windows.Markup.XamlParseException: The current SynchronizationContext may not be used as a task scheduler.

从 main 运行正常。我意识到这不是测试仪的正常使用,但能够选择一个对话框并单击一个按钮以使用测试数据运行它以查看该对话框是否有效是很有值(value)的。但是这个错误阻止我运行它。

在“正确的”线程上运行对话代码是否有技巧?

这是单元测试代码:

[Fact]
static public void Draw2()
{
  var uiThread = new Thread(Draw20);
  uiThread.SetApartmentState(ApartmentState.STA);
  uiThread.Start();
  // Wait for the UI thread to finish
  uiThread.Join();
}
  static void Draw20()
  {
    ModernUIApp1.MainWindow window = new MainWindow();

    System.Windows.Forms.Integration
      .ElementHost
      .EnableModelessKeyboardInterop(window);
    window.ShowDialog();
    window = null;
  }

窗口代码: >

    <mui:ModernWindow.MenuLinkGroups>
    <mui:LinkGroup DisplayName="welcome">
      <mui:LinkGroup.Links>
        <mui:Link DisplayName="home" Source="/Pages/Home.xaml" />
        <mui:Link DisplayName="my page" Source="/Pages/BasicPage.xaml" />
      </mui:LinkGroup.Links>
    </mui:LinkGroup>
    <mui:LinkGroup DisplayName="settings" GroupName="settings">
            <mui:LinkGroup.Links>
                <mui:Link DisplayName="software" Source="/Pages/Settings.xaml" />
            </mui:LinkGroup.Links>
        </mui:LinkGroup>
    </mui:ModernWindow.MenuLinkGroups>

    <mui:ModernWindow.TitleLinks>
        <mui:Link DisplayName="settings" Source="/Pages/Settings.xaml" />
    </mui:ModernWindow.TitleLinks>
</mui:ModernWindow>

最佳答案

为了从单元测试中显示 WPF UI,您需要生成一个新线程,确保它是 single-threaded apartment (STA) ,从该线程创建 UI,显示对话框,然后将结果编码回单元测试线程。

var uiThread = new Thread(MyCreateAndShowUIFunction);
uiThread.SetApartmentState(ApartmentState.STA);
uiThread.Start();

...

// Wait for the UI thread to finish
uiThread.Join();

总的来说,单元测试并不是为了实际启动 UI。那将是一个集成测试,甚至是一个编码的 UI 测试。

关于c# - 从测试运行 WPF 对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19760818/

相关文章:

c# - 如果我将这个序列作为参数传递,我应该检查序列长度吗?

c# - 如何使 WPF StackPanel 适合网格单元格

c# - 禁用点击按钮事件c#

c# - 默认 TextBlock 样式覆盖按钮文本颜色

c# - 使用 MVVM 在 WPF-DataGrid 中进行预选

c# - 来自 xunit MemberData 函数的静态数据被计算两次

c# - 无法将带有 [] 的索引应用于类型为“System.Collections.Generic.IEnumerable<>”的表达式

c# - 如何在同一解决方案中使用来自多个项目的 NLog

c# - 将 xUnit.NET ASP.NET MVC 单元测试添加到现有项目/解决方案

c# - TestDriven.NET 和 native C 库