从单元测试注入时出现此错误。
System.InvalidOperationException: ''NavigationManagerProxy' has not been initialized.'
我的代码:
Services.AddSingleton<NavigationManager>(Mock.Of<NavigationManager>());
从单元测试注入时出现此错误。
System.InvalidOperationException: ''NavigationManagerProxy' has not been initialized.'
我的代码:
Services.AddSingleton<NavigationManager>(Mock.Of<NavigationManager>());
我使用这个类进行单元测试:
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());
在为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");
}
}
我还没有测试过各种场景,但这似乎至少在这种情况下有效。