Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sean-gilliam/8295096124490a20addf81b8e4fad814 to your computer and use it in GitHub Desktop.
Save sean-gilliam/8295096124490a20addf81b8e4fad814 to your computer and use it in GitHub Desktop.

Unit testing with NavigationManager

When writing unit tests for classes / services that contain methods that include NavigationManager, then create a simple derived class to "mock" that functionality.

namespace Your.Namespace.Here;

using Microsoft.AspNetCore.Components;

internal class TestNavigationManager : NavigationManager
{
    public string TestBaseUri { get; } = "https://localhost:9001/";
    private string TestUri { get; } = "https://localhost:9001/";

    public TestNavigationManager(string baseUri = "", string uri = "")
    {
        var baseUrl = !string.IsNullOrWhiteSpace(baseUri) ? baseUri : TestBaseUri;
        var url = !string.IsNullOrWhiteSpace(uri) ? baseUri : TestUri;

        Initialize(baseUrl, url);
    }
}

Then use Dependency Injection to inject the class into the constructor of the class / service under test.

private readonly TestNavigationManager _testNavigationManager;

public SomeTests()
{
    ...
     _testNavigationManager = new TestNavigationManager();
    ...
}

[Fact]
public void SomeTest()
{
    // Arrange
    var service = new SomeService(... other mocked parameters..., _testNavigationManager);
    
    ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment