【发布时间】:2021-08-11 07:56:21
【问题描述】:
在我对xunit wpf tests 的实验之后,我在运行多个测试时遇到了一个问题。
问题是当我在断言中检查 Application.Current.Windows 时。
密码
复制以下代码会导致问题:
测试窗口
<Window x:Class="acme.foonav.Issues.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:acme.foonav.Issues"
mc:Ignorable="d"
Title="TestWindow" Height="450" Width="800">
<Grid>
</Grid>
</Window>
测试
public class WpfFactIssues
{
public WpfFactIssues()
{
if (Application.Current == null)
{
new Application();
}
}
[WpfFact]
public void Test1()
{
TestWindow window = new TestWindow();
Assert.Equal(typeof(TestWindow), Application.Current.Windows[0]?.GetType());
}
[WpfFact]
public void Test2()
{
TestWindow window = new TestWindow();
Assert.Equal(typeof(TestWindow), Application.Current.Windows[0]?.GetType());
}
}
所以在这里,Test1 和 Test2 是相同的。我已经删除了演示此场景所需的任何其他逻辑以专注于实际问题 - 而不是我为什么要这样做!
该场景的目的是检查一个窗口是否已添加到当前应用程序的窗口集合中。
我们正在使用Xunit.StaFact 来管理在 STA 线程上的运行。
问题
如果我执行所有测试(在 Rider 中),那么 Test1 将通过,Test2 将在断言上失败。
System.InvalidOperationException: The calling thread cannot access this object because a different thread owns it.
但是,我可以分别成功执行Test1 和Test2。
执行时,Test1 将在线程 id (Thread.CurrentThread.ManagedThreadId) 为 20 时运行,然后Test2 将继续执行。
当Test2 执行时,Application.Current 被设置为Test1 设置。
我尝试过的
实现IDisposable 并尝试调用Application.Current?.Shutdown() 以拼命尝试使其工作。
public void Dispose()
{
if (Application.Current != null)
{
ManualResetEventSlim manualResetEvent = new ManualResetEventSlim(false);
Application.Current.Exit += (sender, args) => { manualResetEvent.Set(); };
Application.Current?.Shutdown();
manualResetEvent.Wait(TimeSpan.FromSeconds(5));
}
}
这里永远不会引发 Exit 事件。
这将引发不同的异常:
System.InvalidOperationException: Cannot create more than one System.Windows.Application instance in the same AppDomain.
求助!
在同一个类中执行大量方法时,有没有办法在单元测试中使用Application?
更新
目前正在查看:
Manage Application.Current while all tests are running in Test Project
【问题讨论】:
标签: wpf multithreading xunit