Bilal
Bilal

Reputation: 21

Is there a way to read test attribute value like [Owner="Tester"] with c#

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#

Upvotes: 0

Views: 1458

Answers (2)

Bilal
Bilal

Reputation: 21

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

Upvotes: 0

Johnny
Johnny

Reputation: 9509

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)

Upvotes: 1

Related Questions