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

在bUnit中如何验证元素不存在?

解决方案

关于Find()抛出异常的问题

RenderedComponent.Find() 方法在匹配不到元素时会直接抛出异常,不会返回null。要判断元素是否不存在,可改用以下两种方式:

  1. 使用 FindAll() 方法,检查返回集合是否为空:
var liElements = renderedComponent.FindAll("li.validation-message");
Assert.Empty(liElements);
  1. 若使用较新版本Blazor测试库,可用 TryFind() 方法(返回bool表示是否找到,out参数返回元素):
if (renderedComponent.TryFind("li.validation-message", out var li))
{
    Assert.Fail("不应找到验证消息元素");
}

关于HasComponent<>的类型参数问题

HasComponent<T>() 的泛型参数需要传入你要检查的Blazor自定义组件类型,而非原生HTML标签类型。比如要检查是否存在自定义的 ValidationMessageComponent,写法如下:

Assert.True(renderedComponent.HasComponent<ValidationMessageComponent>());

如果只是检查原生HTML元素(如普通<li>),无需使用HasComponent<>(),直接用前面的FindAll()或TryFind()判断即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 00:04:55