23

使用 Xunit,如何获取当前正在运行的测试的名称?

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

编辑:
特别是,我正在寻找 NUnitsTestContext.CurrentContext.Test.Name属性的替代品。

4

3 回答 3

18

您可以使用它BeforeAfterTestAttribute来解决您的问题。有一些方法可以使用 Xunit 来解决您的问题,例如创建 TestClassCommand 或 FactAttribute 和 TestCommand 的子类,但我认为这BeforeAfterTestAttribute是最简单的方法。查看下面的代码。

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);
        }
    }
}
于 2014-09-25T15:41:43.743 回答
6

请参阅 Github 中的类似问题,其中答案/解决方法是在构造函数中使用一些注入和反射。

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);
    }
<...>
  }
于 2019-07-16T23:55:26.587 回答
1

我不能和 xUnit 说话……但这在 VS 测试中确实对我有用。可能值得一试。

参考: 如何从代码中获取当前方法的名称

例子:

[TestMethod]
public void TestGetMethod()
{
    StackTrace st = new StackTrace();
    StackFrame sf = st.GetFrame(0);
    MethodBase currentMethodName = sf.GetMethod();
    Assert.IsTrue(currentMethodName.ToString().Contains("TestGetMethod"));
 }
于 2013-05-10T15:06:37.387 回答