Initialize frame object in view model throws exceptions when running unit test

69 Views Asked by At

I have a WinUi 3 project for a welcome screen.

The following unit test function will throw exceptions, how to resolve these exception?

The welcome screen application runs properly without this problem. The frame object ContentFrame is created in view model to bind the frame control in view. All solutions are welcome, including those solutions that avoid putting a frame object in the view model. Thanks.

 [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);
     }
 } 

View model:

public class WelcomeScreenPageViewModel : ObservableObject
{
     private WelcomeScreenPage welcomeScreenPage;

     public WelcomeScreenPageViewModel(WelcomeScreenPage welcomeScreenPage)
     {
         this.welcomeScreenPage = welcomeScreenPage;
     }

     public Frame ContentFrame = new();  // throws exception
 }

View:

 <Frame x:Name="NavigationFrame" Content="{x:Bind ViewModel.ContentFrame,Mode=TwoWay}" />

Exceptions:

enter image description here

enter image description here

Project source code: https://1drv.ms/u/s!Ap_EAuwC9QkXjBxK2z-0JgrFAxaE?e=fcv96P

1

There are 1 best solutions below

0
Ming On

Here is the solution to solve this problem:

Following this doc: https://devblogs.microsoft.com/ifdef-windows/winui-desktop-unit-tests/

Here is updated test file. Change [TestMethod()] to [UITestMethod()] solve the exception problem.

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);
        }
    }
}