1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

BlazorでNavigationManagerをテストする方法

Posted at

Blazor アプリケーションで NavigationManager を使用したページ遷移のロジックをユニットテストする方法について解説します。

背景

Blazor では、NavigationManager がデフォルトでサービス登録されていますが、インターフェースが実装されていないため、直接テストすることが難しい場合があります。特に、コードビハインドで分離したクラスのメソッドを直接テストする場合、NavigationManager をモックする必要があります。

Bunit を使用すると NavigationManager を直接モックすることが可能ですが、本記事では Bunit を使用せずにモックを作成する方法を説明します。

解決方法

以下の手順で NavigationManager をモックします。

  1. NavigationManager を受け取るフィールドを public にして外部から注入可能にする。
  2. NavigationManager を継承した Fake クラスを作成する。
  3. Fake クラスを外部から注入する。

これにより、テスト時に Fake クラスを使用してページ遷移のロジックを検証できます。

手順 1: フィールドを public にする

テスト対象のクラスで NavigationManager を受け取るフィールドを public に設定します。

public class MyComponent
{
    [inject]
    public NavigationManager NavigationManager { get; set; }

    public void NavigateToPage()
    {
        NavigationManager.NavigateTo("http://localhost/target-page");
    }
}

手順 2: Fake クラスの作成

以下は NavigationManager を継承した Fake クラスの例です。

internal class FakeNavigateManager : NavigationManager
{
    public string? NavigatedTo { get; private set; }

    public FakeNavigateManager()
    {
        Initialize("http://localhost/", "http://localhost/");
    }

    protected override void NavigateToCore(string uri, bool forceLoad)
    {
        NavigatedTo = uri; // 呼ばれたURLを記録
    }
}

手順 3: Fake クラスを外部から注入する

テスト時に Fake クラスをインスタンス化し、テスト対象のクラスに注入します。

[Fact]
public void TestNavigation()
{
    // Arrange
    var fakeNavigationManager = new FakeNavigateManager();
    var myComponent = new MyComponent(fakeNavigationManager);

    // Act
    myComponent.NavigateToPage();

    // Assert
    Assert.Equal("http://localhost/target-page", fakeNavigationManager.NavigatedTo);
}

まとめ

本記事では、Blazor アプリケーションで NavigationManager をモックする方法を紹介しました。この方法を使用することで、ページ遷移のロジックを簡単にユニットテストできます。ぜひ試してみてください。

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?