Get name of running test in Xunit

2020-07-02 09:11发布

问题:

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.

回答1:

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


回答2:

See a similar question in Github where the answer/workaround is to use some injection and reflection i the constructor.

public class Tests
  {
  public Tests(ITestOutputHelper output)
    {
    var type = output.GetType();
    var testMember = type.GetField("test", BindingFlags.Instance | BindingFlags.NonPublic);
    var test = (ITest)testMember.GetValue(output);
    }
<...>
  }


回答3:

I can't speak to xUnit ... but this did work for me in VS Testing. might be worth a shot.

Reference: How to get the name of the current method from code

Example:

[TestMethod]
public void TestGetMethod()
{
    StackTrace st = new StackTrace();
    StackFrame sf = st.GetFrame(0);
    MethodBase currentMethodName = sf.GetMethod();
    Assert.IsTrue(currentMethodName.ToString().Contains("TestGetMethod"));
 }


标签: c# .net tdd xUnit