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

无法从测试用例获取Category值,求助解决空引用异常

问题分析与解决方案

原因定位

你遇到的NullReferenceException是因为TestContext.CurrentContext.Test.Properties.Get("Category")返回了null,直接调用ToString()触发空引用错误。核心问题有两点:

  1. Category获取方式不合理:你的测试类和方法上都标记了[Category](类级别Smoke、方法级别C1879186),而Properties.Get("Category")仅返回单个对象,可能优先取到类级别的Smoke,或在并行场景下无法正确绑定方法级别的属性;
  2. 缺失空值校验:没有先判断返回值是否为空就执行后续操作,直接引发异常。

修正方案

1. 可靠获取目标Category(测试用例ID)

改用GetAll("Category")获取所有Category集合,再筛选出带C前缀的测试用例ID,避免层级冲突:

// 获取所有Category,筛选出带C前缀的项
var categories = TestContext.CurrentContext.Test.Properties.GetAll("Category");
var testCaseCategory = categories.FirstOrDefault(c => c.ToString().StartsWith("C"));

if (testCaseCategory == null)
{
    Console.WriteLine("未找到带C前缀的测试用例Category");
    return; // 或执行其他兜底逻辑
}

var testCase = testCaseCategory.ToString().Replace("C", "");
Console.WriteLine(testCase);

2. 排查并行测试的上下文影响

你的测试类标记了[Parallelizable(ParallelScope.Self)],若问题仍存在,可以:

  • 临时注释[Parallelizable]关闭并行,验证是否是并行导致的TestContext绑定异常;
  • 确认使用的NUnit版本是否支持并行场景下的TestContext正确获取。

3. 空值安全的完整TearDown代码片段

修改后的关键部分代码:

// ... 其他TestRail请求代码 ...

// 获取测试用例ID
var categories = TestContext.CurrentContext.Test.Properties.GetAll("Category");
var testCaseCategory = categories.FirstOrDefault(c => c?.ToString().StartsWith("C") ?? false);

if (testCaseCategory == null)
{
    Console.WriteLine("未找到有效的测试用例Category");
    return;
}

var testCase = testCaseCategory.ToString().Replace("C", "");
Console.WriteLine(testCase);

// ... 后续TestRail结果提交代码 ...

额外说明

你提到相同代码在其他测试方法中能运行,大概率是那些方法只有方法级别的Category,Get("Category")刚好返回目标值。但在当前类存在两级Category的场景下,Get的行为不稳定,因此用GetAll+筛选的方式更可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:30:42