如何在bUnit测试中模拟注入的ILocalStorageService依赖?
我正在用bUnit测试Blazor组件,在模拟组件中注入的ILocalStorageService依赖时遇到了问题。组件中的注入代码如下:
[Inject] public ILocalStorageService LocalStorage { get; set; } = null!;
创建被测组件实例的基础代码是这样的:
TestComponentSender cut = RenderComponent<TestComponentSender>(ps => ps .Add(p => p.NotificationHelper, new TestNotificationHelper()) ).Instance;
由于LocalStorage是注入属性而非组件参数,我没法像处理NotificationHelper那样用Add方法直接传入。
我尝试过几种方法,但都失败了:
尝试1:直接注册服务
在创建组件前添加以下代码:
Services.AddScoped<ILocalStorageService>();
运行测试时抛出异常:
Cannot instantiate implementation type 'Blazored.LocalStorage.ILocalStorageService' for service type 'Blazored.LocalStorage.ILocalStorageService'
尝试2:用NSubstitute手动赋值
引用NSubstitute NuGet包后,在创建组件实例后手动赋值:
cut.LocalStorage = Substitute.For<ILocalStorageService>();
依然抛出异常:
Cannot provide a value for property 'LocalStorage' on type 'InspiredGiving.Crm.Areas.General.Shared.TestComponentSender'. There is no registered service of type 'Blazored.LocalStorage.ILocalStorageService'.
更新:尝试bUnit的Blazored.LocalStorage扩展
根据Egil的回答,我安装了bUnit相关测试包,并参照示例编写了代码:
TestComponentSender cut = RenderComponent<TestComponentSender>(ps => ps .Add(p => p.NotificationHelper, new TestNotificationHelper()) ).Instance; cut.LocalStorage = this.AddBlazoredLocalStorage();
还是遇到相同的异常:
System.InvalidOperationException: Cannot provide a value for property 'LocalStorage' on type 'InspiredGiving.Crm.Areas.General.Shared.TestComponentSender'. There is no registered service of type 'Blazored.LocalStorage.ILocalStorageService'
之后又尝试了Robert Harvey提到的方法:
Services.AddScoped<ILocalStorageService>(_ => this.AddBlazoredLocalStorage());
结果依旧抛出上述异常。
请问该如何正确模拟这个注入的依赖?
内容的提问来源于stack exchange,提问作者Avrohom Yisroel

