Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
lawrence_shaun_introducing_net_maui_build_and_deploy_crosspl.pdf
Скачиваний:
46
Добавлен:
26.06.2023
Размер:
5.15 Mб
Скачать

Chapter 12 Testing

<IsPackable>false</IsPackable>

</PropertyGroup>

Now you have set up everything ready to begin writing and running your unit tests.

Testing Your View Models

The MVVM architecture lends itself very well to unit testing each individual component.

First, you need to create a ViewModels folder in your WidgetBoard.Tests project and then add a new class file called

BoardDetailsPageViewModelTests.cs. It is good practice to keep folders and tests named similarly to the code that they are testing to make it easier to organize and locate.

Now you can add in your first set of tests.

Testing BoardDetailsPageViewModel

Inside the class file that you just created, add the following:

[Fact]

public void SaveCommandCannotExecuteWithoutBoardName()

{

var viewModel = new BoardDetailsPageViewModel(null, null);

Assert.Null(viewModel.BoardName);

Assert.False(viewModel.SaveCommand.CanExecute(null));

}

[Fact]

public void SaveCommandCanExecuteWithBoardName()

372

Chapter 12 Testing

{

var viewModel = new BoardDetailsPageViewModel(null, null);

viewModel.BoardName = "Work";

Assert.True(viewModel.SaveCommand.CanExecute(null));

}

Testing INotifyPropertyChanged

I covered in Chapter 4 that INotifyPropertyChanged serves as the mechanism to keep your views and view models in sync; therefore, it can be really useful to verify that your view models are correctly implementing

INotifyPropertyChanged by ensuring that it raises the PropertyChanged event when it should.

The following test shows how to create an instance of the

BoardDetailsPageViewModel, subscribe to the PropertyChanged event, modify a property that you expect to fire the PropertyChanged event, and then Assert that the event was invoked:

[Fact]

public void SettingBoardNameShouldRaisePropertyChanged()

{

var invoked = false;

var viewModel = new BoardDetailsPageViewModel(null, null);

viewModel.PropertyChanged += (sender, e) =>

{

if (e.PropertyName.Equals(nameof(BoardDetailsPageView Model.BoardName)))

{

invoked = true;

}

373