是否可以通过反射获取NUnit自定义属性PropertyAttribute的值?

问题描述 投票:0回答:1

我有以下类似内容

[TestFixture]
public class Test
{
    [Test]
    [Property("Test", "TEST-1234")]
    public void TestOne()
    {
        Assert.IsTrue(true);
    }

    [Test]
    [Property("Test", "TEST-5678")]
    public void TestTwo()
    {
        Assert.IsTrue(true);
    }
}

我需要获取属性Test的值,即我需要通过反射获取TEST-1234。我知道可以在运行时使用TestContext.CurrentContext.Test.Properties["Test"])之类的东西来获取它,但这对我没有帮助。

我已经尝试过几种方法,例如

test.GetCustomAttributes(typeof(NUnit.Framework.PropertyAttribute)).ToList()[0]

这使我获得了属性对象本身,但是我无法访问值本身,这可能吗?

c# nunit nunit-3.0
1个回答
0
投票

因此,假设您有一个在给定方法中找到的属性属性数组。通过反射指定类型PropertyAttribute可以得到它们,因此即使数组为Attribute[],也知道它们是什么。

因此,您需要找到Name属性为“测试”以及分配给该属性的值的所有属性(或者,如果需要,则找到第一个属性。)>

[[顺便说一句,“ Test”在这里对我来说似乎是个坏名字,因为NUnit有很多东西叫做“ Test”,而您自己的测试代码也可能做得很好。但是我们将使用该名称作为示例。]

您需要做这样的事情...

for each (PropertyAttribute attr in attrs) // attrs filled by you already
{
     if (attr.Name == "Test")
         testValue = attr.Value;

     // Process the value as you want. If there's just one and this is in
     // a function call, you can return it. If you are doing something else,
     // do it here and then `break` to exit the loop
}

您可以使用System.Linq使用更少的代码来完成此操作,但我认为循环将帮助您更清楚地了解必须执行的操作。

© www.soinside.com 2019 - 2024. All rights reserved.