4

从单元测试注入时出现此错误。

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

我的代码:

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

2 回答 2

5

我使用这个类进行单元测试:

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

然后在测试内部设置如下:

Services.AddSingleton<NavigationManager>(new TestNav());
于 2020-10-21T21:19:19.660 回答
2

在为Blazing Pizza Workshop编写测试时,我们使用了这个(类似于@Akinzekeel 的代码):

    public class FakeNavigationManager : NavigationManager
    {
        private readonly ITestRenderer renderer;

        public FakeNavigationManager(ITestRenderer renderer)
        {
            Initialize("http://localhost/", "http://localhost/");
            this.renderer = renderer;
        }

        protected override void NavigateToCore(string uri, bool forceLoad)
        {
            Uri = ToAbsoluteUri(uri).ToString();

            renderer.Dispatcher.InvokeAsync(
                () => NotifyLocationChanged(isInterceptedLink: false));
        }
    }

测试看起来像这样:

@inherits TestContext
@code {
    private NavigationManager navigationManager; 

    public MainLayoutTests()
    {
        Services.AddSingleton<NavigationManager, FakeNavigationManager>();
        navigationManager = Services.GetService<NavigationManager>();        
    }

    [Fact]
    public void MyOrdersNavigationItem_Is_Marked_As_Active_When_Viewing_MyOrdersPage()
    {
        var cut = Render(@<MainLayout />);

        navigationManager.NavigateTo("myorders");

        cut.Find("a[href=myorders]")
            .ClassList
            .Should()
            .Contain("active");
    }
}

我还没有测试过各种场景,但这似乎至少在这种情况下有效。

于 2021-02-19T16:27:43.187 回答