Search code examples
c#blazorxunitblazor-server-sidebunit

How to inject NavigationManager in bunit Blazor component unit test


I am getting this error when injecting from unit test.

System.InvalidOperationException: ''NavigationManagerProxy' has not been initialized.'

My code:

Services.AddSingleton<NavigationManager>(Mock.Of<NavigationManager>());         

Solution

  • I use this class for my unit tests:

    internal class TestNav : NavigationManager
    {
        public TestNav()
        {
            Initialize("https://unit-test.example/", "https://unit-test.example/");
        }
    
        protected override void NavigateToCore(string uri, bool forceLoad)
        {
            NotifyLocationChanged(false);
        }
    }
    

    Then inside the test set it up like this:

    Services.AddSingleton<NavigationManager>(new TestNav());