so cal cheesehead
so cal cheesehead

Reputation: 2573

Is it possible to get the value of NUnit custom attribute PropertyAttribute via reflection?

I have something like the following

[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);
    }
}

I need to get the value of the attribute Test i.e I need to get TEST-1234 via reflection. I know that it's possible to get it at runtime with something like TestContext.CurrentContext.Test.Properties["Test"]) but that doesn't help me.

I've tried several methods like

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

which gets me the attribute object itself but I cannot access the value itself, is this possible?

Upvotes: 0

Views: 1161

Answers (1)

Charlie
Charlie

Reputation: 13681

So, let's assume you have an array of property attributes, found on a given method. You got them by reflection specifying the type PropertyAttribute so you know that's what they are, even though the array is Attribute[].

So you need to find all attributes (or the first attribute if you just want one) with a Name property of "Test" as well as the value assigned to that property.

[BTW, "Test" seems a pretty bad name to me here, since NUnit has so many things called "Test" and your own test code probably does as well. But we will stay with that name for the example.]

You need to do something like this...

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
}

You can do it with less code using System.Linq, but I think the loop will help you see more clearly what has to be done.

Upvotes: 1

Related Questions