1

        [Fact(DisplayName = "Test Demo Display Name")]
        [Trait("Category", "Internal")]
        [Trait("Category", "All")]
        public void Demo()
        {

            // I like to get the DisplayName 'Test Demo Display Name' here(inside this function) for    furthur processing.


        }

I like to get the DisplayName 'Test Demo Display Name' here(inside function) for further processing. How to do that? I know there are some option to get the Traits details using the TraitsHelper class. Is there any similar approach available for Facts attribute as well.

Hashili
  • 113
  • 16

1 Answers1

2

I'm not sure if xUnit has some specific mechanism to help you do this, but you can easily write your own helper to do this.

using System.Diagnostics;
using System.Linq;
static class XUnitHelper
{
    internal static string FactDisplayName()
    {
        var frame = new StackFrame(1, true);
        var method = frame.GetMethod();
        var attribute = method.GetCustomAttributes(typeof(Xunit.FactAttribute), true).First() as Xunit.FactAttribute;

        return attribute.DisplayName;
    }
}

Inside your unit test method, call XUnitHelper.FactDisplayName(). Of course this won't work if there is any nesting - for example, if you call this helper in another method which is itself called from the unit test method decorated by Fact. To handle a case like that, you'd have to write more complicated code which traversed the stack (in fact, that's why the 1 is passed to the constructor of StackFrame; we want to skip past the stack information for the helper method itself).

jamarchist
  • 46
  • 3
  • Currently i am using below code for getting the 'DisplayName'. I am looking for any specific xUnit functions for doing this. MethodBase method = MethodBase.GetCurrentMethod(); FactAttribute attr = (FactAttribute)method.GetCustomAttributes(typeof(FactAttribute), true)[0]; string nameForReport = attr.DisplayName; – Hashili Feb 04 '20 at 08:27