Search code examples
c#.nettddxunit

Get name of running test in Xunit


Using Xunit, how can I get the name of the currently running test?

  public class TestWithCommonSetupAndTearDown : IDisposable
  {
    public TestWithCommonSetupAndTearDown ()
    {
      var nameOfRunningTest = "TODO";
      Console.WriteLine ("Setup for test '{0}.'", nameOfRunningTest);
    }

    [Fact]
    public void Blub ()
    {
    }

    public void Dispose ()
    {
      var nameOfRunningTest = "TODO";
      Console.WriteLine ("TearDown for test '{0}.'", nameOfRunningTest);
    }
  }

Edit:
In particular, I am looking for a replacement for NUnits TestContext.CurrentContext.Test.Name property.


Solution

  • You can use BeforeAfterTestAttribute to resolve your case. There are some ways to address your issue using Xunit, which would be to make sub-class of TestClassCommand, or FactAttribute and TestCommand, but I think that BeforeAfterTestAttribute is the simplest way. Check out the code below.

    public class TestWithCommonSetupAndTearDown
    {
        [Fact]
        [DisplayTestMethodName]
        public void Blub()
        {
        }
    
        private class DisplayTestMethodNameAttribute : BeforeAfterTestAttribute
        {
            public override void Before(MethodInfo methodUnderTest)
            {
                var nameOfRunningTest = "TODO";
                Console.WriteLine("Setup for test '{0}.'", methodUnderTest.Name);
            }
    
            public override void After(MethodInfo methodUnderTest)
            {
                var nameOfRunningTest = "TODO";
                Console.WriteLine("TearDown for test '{0}.'", methodUnderTest.Name);
            }
        }
    }