0

I want to know if there is a way to read test attribute value? For example

[TestMethod , TestCategory ("Smoke Test"), Priority (1), Owner ("Tester")]

if there is way to get the value of test owner attribute as string using c#

Johnny
  • 8,939
  • 2
  • 28
  • 33
Bilal
  • 21
  • 3
  • 3
    Possible duplicate of [Read the value of an attribute of a method](https://stackoverflow.com/questions/2493143/read-the-value-of-an-attribute-of-a-method) – Mark Benningfield Apr 09 '19 at 20:35
  • I have 1100+ test methods in different classes with different owner names assigned to them. Need some generic method to get owner attribute value. – Bilal Apr 09 '19 at 20:41

2 Answers2

1

I think TestContext could help you.

var category = (string) TestContext.CurrentContext.Test.Properties.Get("Category");

I am speaking about runtime, otherwise, you could use this(tnx to Mark Benningfield)

Johnny
  • 8,939
  • 2
  • 28
  • 33
  • thank you for help, i used Mikael Engver solution [link](https://stackoverflow.com/questions/2493143/read-the-value-of-an-attribute-of-a-method) – Bilal Apr 10 '19 at 14:42
0
public class Helper
    {
        public static TValue GetOwnerAttributeValue<TValue>(MethodBase method, Func<OwnerAttribute, TValue> valueSelector) 
        {
           return method.GetCustomAttributes(typeof(OwnerAttribute), true).FirstOrDefault() is OwnerAttribute attr ? valueSelector(attr) : default(TValue);
        }

    }

Called this way

var testMethod = new StackTrace().GetFrame(1)
            .GetMethod();
        var testAuthor = Helper.GetOwnerAttributeValue(testMethod, x => x.Owner);
Bilal
  • 21
  • 3
  • Better way to call it var owner = Helper.GetOwnerAttributeValue(GetType().GetMethod(TestName), x => x.Owner); – Bilal Apr 11 '19 at 13:41