[英]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>());
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());
While writing tests for the Blazing Pizza Workshop , we used this (similar to @Akinzekeel's code):在为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));
}
}
and the tests look like this:测试如下所示:
@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");
}
}
I haven't tested all sorts of scenarios, but this seems to work in this case at least.我还没有测试过各种场景,但这至少在这种情况下似乎有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.