我有一个用于欢迎屏幕的 WinUi 3 项目。
以下单元测试函数会抛出异常,如何解决这些异常?
欢迎屏幕应用程序运行正常,没有这个问题。框架对象
ContentFrame
是在视图模型中创建的,用于绑定视图中的框架控件。欢迎所有解决方案,包括那些避免将框架对象放入视图模型中的解决方案。谢谢。
[TestClass()]
public class WelcomeScreenPageViewModelTests
{
[TestMethod()]
public void WelcomeScreenPageViewModelTest()
{
WelcomeScreenPage welcomeScreenPage = new WelcomeScreenPage();
WelcomeScreenPageViewModel _viewModel = new WelcomeScreenPageViewModel(welcomeScreenPage);// throw exceptions.
Assert.AreEqual(_viewModel.IsCheckBoxVisible, false);
Assert.AreEqual(_viewModel.IsBackButtonVisible, false);
Assert.AreEqual(_viewModel.NextButtonText, "Next");
Assert.AreEqual(_viewModel.CurrentPageIndex, 0);
}
}
查看模型:
public class WelcomeScreenPageViewModel : ObservableObject
{
private WelcomeScreenPage welcomeScreenPage;
public WelcomeScreenPageViewModel(WelcomeScreenPage welcomeScreenPage)
{
this.welcomeScreenPage = welcomeScreenPage;
}
public Frame ContentFrame = new(); // throws exception
}
查看:
<Frame x:Name="NavigationFrame" Content="{x:Bind ViewModel.ContentFrame,Mode=TwoWay}" />
例外:
项目源码: https://1drv.ms/u/s!Ap_EAuwC9QkXjBxK2z-0JgrFAxaE?e=fcv96P
解决这个问题的方法如下:
按照本文档: https://devblogs.microsoft.com/ifdef-windows/winui-desktop-unit-tests/
这里是更新的测试文件。将[TestMethod()]更改为[UITestMethod()]解决异常问题。
namespace WelcomeScreen.UnitTest
{
[TestClass()]
public class WelcomeScreenPageViewModelTests
{
[UITestMethod()]
public void WelcomeScreenPageViewModelTest()
{
WelcomeScreenPage welcomeScreenPage = new WelcomeScreenPage();
WelcomeScreenPageViewModel _viewModel = new WelcomeScreenPageViewModel(welcomeScreenPage);
Assert.AreEqual(_viewModel.IsCheckBoxVisible, false);
Assert.AreEqual(_viewModel.IsBackButtonVisible, false);
Assert.AreEqual(_viewModel.NextButtonText, "Next");
// Assert.AreEqual(_viewModel.PreviousPageIndex, -1);
Assert.AreEqual(_viewModel.CurrentPageIndex, 0);
}
}
}