Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 42 ยท Testing and Publishing

Unit Testing View Models

Test .NET MAUI view models without a device using xUnit, fake services, async commands and PropertyChanged assertions; includes a runnable mini test runner you can experiment with.

The best reason to use MVVM is testability. A view model is a plain C# class: it holds state, exposes commands and talks to services through interfaces. None of that needs a screen, an emulator or the MAUI runtime. You can test hundreds of behaviors in a second on a build server. This lesson shows how to structure a test project, how to fake the outside world, and how to test properties, commands and async code.

The real test tooling (xUnit, dotnet test, the test project referencing a MAUI app) cannot run on this site, so it is shown read-only. The runnable examples use a tiny hand-written test runner and the same view model code, so you can see the patterns work.

Where tests live

Create a separate class library or xUnit project next to the app, and put the code you want to test in a project both can reference:

TEXT
MyApp.sln
  MyApp/               (the MAUI app: pages, XAML, platform code)
  MyApp.Core/          (view models, services, models: plain net10.0)
  MyApp.Tests/         (xUnit, references MyApp.Core)

A test project cannot easily reference a MAUI app project, because the app targets platform frameworks (net10.0-android and so on). Moving view models and services into a net10.0 class library avoids the problem and keeps the logic free of UI types. Aim for no using Microsoft.Maui... in MyApp.Core (except Microsoft.Maui.Graphics if you need colors).

A testable view model

Services come in through the constructor as interfaces, so a test can pass a fake:

C#
public interface IWeatherService
{
    Task<double> GetTemperatureAsync(string city, CancellationToken ct = default);
}

public class WeatherViewModel : INotifyPropertyChanged
{
    private readonly IWeatherService _service;
    private string _city = "";
    private string _status = "Enter a city";

    public WeatherViewModel(IWeatherService service)
    {
        _service = service;
        LoadCommand = new AsyncRelayCommand(LoadAsync, () => !string.IsNullOrWhiteSpace(City));
    }

    public string City
    {
        get => _city;
        set { _city = value; OnPropertyChanged(); LoadCommand.RaiseCanExecuteChanged(); }
    }

    public string Status { get => _status; private set { _status = value; OnPropertyChanged(); } }
    public AsyncRelayCommand LoadCommand { get; }

    private async Task LoadAsync()
    {
        try
        {
            Status = "Loading...";
            double t = await _service.GetTemperatureAsync(City);
            Status = $"{City}: {t:0.#} C";
        }
        catch (HttpRequestException)
        {
            Status = "Network error";
        }
    }

    public event PropertyChangedEventHandler? PropertyChanged;
    private void OnPropertyChanged([CallerMemberName] string? name = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}

Nothing in it depends on MAUI. (With the MVVM Toolkit, [ObservableProperty] and [RelayCommand] generate most of this boilerplate; the tests look the same.)

Writing xUnit tests

xUnit marks tests with [Fact] (one case) and [Theory] (many cases from data). A fake is a small class that implements the interface:

C#
public class WeatherViewModelTests
{
    private class FakeWeather : IWeatherService
    {
        public double Result { get; set; } = 20;
        public Exception? Throw { get; set; }
        public Task<double> GetTemperatureAsync(string city, CancellationToken ct = default)
            => Throw is null ? Task.FromResult(Result) : Task.FromException<double>(Throw);
    }

    [Fact]
    public async Task Load_ShowsTemperature()
    {
        var vm = new WeatherViewModel(new FakeWeather { Result = 21.5 }) { City = "Oslo" };

        await vm.LoadCommand.ExecuteAsync();

        Assert.Equal("Oslo: 21.5 C", vm.Status);
    }

    [Fact]
    public async Task Load_ShowsError_WhenNetworkFails()
    {
        var vm = new WeatherViewModel(new FakeWeather { Throw = new HttpRequestException() }) { City = "Oslo" };

        await vm.LoadCommand.ExecuteAsync();

        Assert.Equal("Network error", vm.Status);
    }

    [Theory]
    [InlineData("", false)]
    [InlineData("  ", false)]
    [InlineData("Rome", true)]
    public void LoadCommand_CanExecute_OnlyWithCity(string city, bool expected)
    {
        var vm = new WeatherViewModel(new FakeWeather()) { City = city };
        Assert.Equal(expected, vm.LoadCommand.CanExecute(null));
    }
}

Run them with dotnet test. Name tests for the behavior (Load_ShowsError_WhenNetworkFails) so a failing name explains the problem.

Arrange, Act, Assert

Every test has three parts: arrange the objects and fakes, act by calling one thing, assert the visible result. One logical behavior per test keeps failures easy to read.

Fakes, stubs and mocks

Test double What it does Example
Stub Returns canned answers Result = 21.5
Fake A small working replacement An in-memory repository
Mock Records calls so you can verify them "was SaveAsync called once?"

A hand-written fake is often clearer than a mocking library. If you prefer a library, NSubstitute and Moq create doubles from interfaces. Prefer asserting on outcomes (the Status text) over asserting on exact call sequences; the former survives refactoring.

MAUI-specific services (Preferences, Connectivity, Geolocation, FileSystem) are interfaces in Microsoft.Maui.Storage and Microsoft.Maui.Networking (IPreferences, IConnectivity), so you inject them and replace them in tests, instead of calling the static Preferences.Default inside the view model.

Testing property change notifications

Binding relies on PropertyChanged. Record the names that were raised:

C#
[Fact]
public void SettingCity_RaisesPropertyChanged()
{
    var vm = new WeatherViewModel(new FakeWeather());
    var raised = new List<string?>();
    vm.PropertyChanged += (_, e) => raised.Add(e.PropertyName);

    vm.City = "Paris";

    Assert.Contains(nameof(vm.City), raised);
}

A mini test runner you can play with

xUnit finds [Fact] methods by reflection. The next TryIt does the same in about twenty lines, so you can see the mechanism, and it contains the view model and tests from above (the async command is simplified).

C# Stand-in: a view model and a tiny test runner

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Change the expected text in the last test to make it pass, or break the view model and watch the others fail. That feedback loop is the whole point.

Testing time and randomness

Code that calls DateTime.Now, Random or Task.Delay is hard to test. Inject them: .NET provides TimeProvider (with FakeTimeProvider in the Microsoft.Extensions.TimeProvider.Testing package) so a test can move the clock instantly.

C# Stand-in: a controllable clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

What not to unit test

  • XAML layout and colors (use manual checks or UI tests, see Debugging and Diagnostics).
  • The framework itself (does Entry raise TextChanged?).
  • Trivial properties with no logic.

Focus on rules: validation, calculations, state transitions, error handling, and the order of calls to services.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why put view models in a separate net10.0 class library?

    The MAUI app targets platform frameworks, which makes it awkward to reference from tests. Plain net10.0 libraries are easy to test.
  2. 2. How does a view model become testable when it needs a web service?

    Constructor injection of an interface lets production code pass the real service and tests pass a controlled fake.
  3. 3. What does [Theory] with [InlineData] do in xUnit?

    A theory is a parameterized test: each InlineData row is one case.
  4. 4. Which assertion style is more robust against refactoring?

    Outcome assertions survive internal changes. Tests tied to call sequences break whenever the implementation changes.

Summary

  • Keep logic in view models and services in a plain class library; the MAUI app only holds pages and platform code.
  • Inject interfaces (including IPreferences, IConnectivity and a clock) and use fakes in tests.
  • Test properties, commands, CanExecute, error handling and PropertyChanged; follow Arrange, Act, Assert.
  • Use [Fact] for single cases and [Theory] for tables of inputs.

Next: Debugging and Diagnostics