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

使用NUnit TestCase时无法获取CategoryName的问题求助

解决NUnit参数化测试(TestCase)中无法获取Category的问题

问题原因

使用TestCase特性时,TestContext.CurrentContext.Test指向的是当前运行的参数化测试实例,而你标记的Category特性属于原始测试方法,实例的Properties不会自动继承方法级别的Category属性,导致获取到空值。

修复代码

将获取属性的逻辑从测试实例改为测试方法:

// 从原始测试方法的属性中获取Category,而非参数化实例
var methodProperties = NUnit.Framework.TestContext.CurrentContext.Test.Method.Properties;
var lstCategories = (System.Collections.IList)methodProperties["Category"];

// 增加空值判断避免异常
if (lstCategories != null && lstCategories.Count > 0)
{
    string categoryName = (string)lstCategories[0];
    // 你的业务逻辑
}

补充说明

  • 所有方法级别的特性(包括Category)都会存储在Test.Method.Properties中,参数化测试实例仅保留与参数相关的属性
  • 建议始终添加空值检查,防止因未标记Category导致的空引用异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 13:20:28