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);
...
}