我在 WPF Windows 周围的其他一些单元测试中取得了成功。这个有我。
我在 xunit
中有一个 dotnet core 5
测试项目,它有一个 Window。该测试将框架的内容设置为新页面。但是,检查内容不为空的断言将不起作用,因为 ViewNavigator 的内容为空。
这是使用 Xunit.StaFact 来允许在 STA 线程下运行测试。
<Window x:Class="acme.foonav.FrameNavigationWindow"
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"
mc:Ignorable="d"
Title="FrameNavigationWindow" Height="450" Width="800">
<StackPanel>
<Frame x:Name="ViewNavigator"></Frame>
</StackPanel>
</Window>
[UIFact]
public void Navigate_To_Pages()
{
FrameNavigationWindow window = new();
var monitor = new ManualResetEventSlim(false);
window.ViewNavigator.NavigationService.Navigated += (sender, args) => monitor.Set();
window.ViewNavigator.ContentRendered += (sender, args) => monitor.Set();
// set content here
window.ViewNavigator.Content = new PageNoVm1();
monitor.Wait(TimeSpan.FromSeconds(5));
// content always null
Assert.Equal(typeof(PageNoVm1), window.ViewNavigator.Content.GetType());
}
只是一个空白页。
<Page x:Class="acme.foonav.Pages.PageNoVm1"
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.Pages"
mc:Ignorable="d"
Title="PageNoVm1" Height="450" Width="800">
<Grid>
</Grid>
</Page>
我没有发现任何明显的错误。
** 更新 **
我尝试使用不同风格的 window.Dispatcher.Invoke
来设置 Content
:
var monitor = new ManualResetEventSlim(false);
window.ViewNavigator.NavigationService.Navigated += (sender, args) => monitor.Set();
window.ViewNavigator.ContentRendered += (sender, args) => monitor.Set();
var page = new PageNoVm1();
window.Dispatcher.Invoke(() => window.ViewNavigator.Content = page);
monitor.Wait(TimeSpan.FromSeconds(3));
答案 0 :(得分:1)
你为什么要同步阻塞 3 或 5 秒?如果 WPF 需要一些时间,您不会以这种方式喂它 - 您会饿死它。
尝试将测试方法改为 async,然后使用 await 给 WPF 时间:
-monitor.Wait(TimeSpan.FromSeconds(5));
+await Task.Delay(5000);
我不知道这是否能解决问题,但总的来说这是暂停执行的更好方法。