You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8 Blazor bUnit测试服务注入失败问题求助

解决bUnit测试中服务注册的问题

问题根源

你报错的核心原因是调用时机和访问对象错误:Services是TestContext实例的专属属性,你在创建TestContext实例之前就直接调用Services.AddSingleton,且没有通过具体的TestContext对象访问,自然找不到AddSingleton方法。

修正后的测试代码

把服务注册逻辑移到TestContext实例创建之后,通过ctx.Services来操作:

public void ItemsAreShowedOnOverview() 
{
    using var ctx = new TestContext();
    // 正确的服务注册方式:通过TestContext实例的Services属性
    ctx.Services.AddSingleton<CartService>(new CartService());
    
    var cutOverview = ctx.RenderComponent<Overview>();
    cutOverview.Find("p").MarkupMatches("<p>Taktiles Messgerät</p>");
}

额外说明

  • 如果你的CartService有构造函数依赖,可使用工厂重载来注册,示例:
    ctx.Services.AddSingleton<CartService>(sp => new CartService(sp.GetRequiredService<SomeDependency>()));
    
  • 若CartService存在公共无参构造函数,也可以简化为ctx.Services.AddSingleton<CartService>(),bUnit会自动完成实例化。

内容的提问来源于stack exchange,提问作者Mephistio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 18:45:56