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

Chapter 12 Testing

after: TimeSpan.FromSeconds(5));

var locationService = MockLocationService.ThatReturns( new Location(0.0, 0.0),

after: TimeSpan.FromSeconds(2));

var viewModel = new WeatherWidgetViewModel( weatherForecastService, locationService);

await viewModel.InitializeAsync();

Assert.Equal(State.Loaded, viewModel.State); Assert.Equal("Sunshine", viewModel.Weather);

}

This final test, as the name implies, verifies that if a valid forecast is returned from the IWeatherForecastService implementation, the view model State will be set to Loaded and the Weather will be correctly set.

Testing Your Views

It is possible to write unit tests that will verify the behavior of your views.

Creating Your ClockWidgetViewModel Mock

In order to verify your ClockWidgetView, you need to provide it with a view model. Your ClockWidgetViewModel currently has some complexities in it that will make it difficult to use in the test. It displays the current date/time. Let’s create a mock to remove this potential difficulty. Inside your Mocks folder, add a new class file called MockClockWidgetViewModel.cs and modify the contents to match the following:

using WidgetBoard.ViewModels;

380

Chapter 12 Testing

namespace WidgetBoard.Tests.Mocks;

public class MockClockWidgetViewModel : IWidgetViewModel

{

public int Position { get; set; }

public string Type => "Mock";

public MockClockWidgetViewModel(DateTime time)

{

Time = time;

}

public DateTime Time { get; }

public Task InitializeAsync() => Task.CompletedTask;

}

Now you can use this in your unit tests to verify that your ClockWidgetView binds correctly to its view model.

Creating Your View Tests

First, create a Views folder in your WidgetBoard.Tests project and then add a new class file called ClockWidgetView.cs.

using WidgetBoard.Tests.Mocks; using WidgetBoard.Views;

namespace WidgetBoard.Tests.Views;

public class ClockWidgetViewTests

{

[Fact]

public void TextIsUpdatedByTimeProperty()

{

381