c# - 如何使用反射检索测试夹具的类别属性?
问题描述
我有一个 NUnit 测试项目。因为我有这样的课
[TestFixture]
[Category("A")]
public class SmokeTest
{
}
如果您注意到,该类有一个 Category 属性,称为 Category("A")。我想使用反射检索类别属性的值。为此,我正在尝试以下代码:
public void MyMethod()
{
Assembly executingAssembly = Assembly.LoadFrom("dllpath");
var types = executingAssembly.GetTypes();
foreach (Type type in types)
{
var testFixtureAttrList = Attribute.GetCustomAttributes(type, typeof(TestFixtureAttribute));
if (testFixtureAttrList.Length > 0)
{
CategoryAttribute[] categoryAttributes = (CategoryAttribute[])Attribute.GetCustomAttributes(type, typeof(CategoryAttribute));
foreach (CategoryAttribute attribute in categoryAttributes)
{
Console.WriteLine($"CategoryAttribute :: Name: {attribute.Name}");
}//FOR-EACH ENDS
}
}
}
但是,到目前为止,我还无法使用此代码检索类别属性。那么,我应该怎么做才能检索 Category 属性?
我的代码是用 C# 编写的。我的解决方案是使用 .NET Core 3.1 构建的
解决方案
更简单的...
TestContext
运行该方法时,您可以使用类别OneTimeSetUp
...
...
IEnumerable<CategoryAttribute> fixtureCategories;
[OneTimeSetUp]
public void MyOneTimeSetUpMethod()
{
fixtureCategories =
TestContext.CurrentContext.Test.Properties["Category"]);
}
推荐阅读
- r - 提取数据帧中最大单调递增/递减序列的元素
- javascript - 如何映射列表并在其中实现异步?
- database - 对于由多个不同服务共享的简单数据库(本质上只是一个键/值存储),最好的 AWS 服务是什么?
- node.js - 使用 Node/Express 路由器模块为 Create-React-App 应用程序提供服务
- python - 如何重新训练/更新 keras 模型?
- docker - Docker构建一个引用不同文件夹中项目的.net核心应用程序
- c# - Unity 玩家与水平小碰撞器的碰撞
- python - 无法在 Django 后端散列密码
- json - 无论字典中是否缺少值,如何将 JSON 字典对象抓取到熊猫数据框中?
- python - Python ctypes 从 void* 创建字节数组