【问题标题】:Get name of running test in Xunit获取 Xunit 中运行测试的名称
【发布时间】:2013-05-05 06:58:07
【问题描述】:

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

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

【问题讨论】:

    标签: c# .net tdd xunit


    【解决方案1】:

    我无法与 xUnit 交谈……但这在 VS 测试中确实对我有用。可能值得一试。

    参考: How to get the name of the current method from code

    例子:

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

    【讨论】:

    • 感谢您的回答。我知道这个选项(现在正在使用)并正在寻找另一个选项。
    • 在给出这个答案时不确定它是否存在,但是,如果您使用的是 MSTest,您可以依赖测试类中的 TestContext 实例,该实例将自动设置我的测试运行器给您正在运行的测试名称等。
    【解决方案2】:

    您可以使用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);
            }
        }
    }
    

    【讨论】:

    • 为我工作。该属性可以应用于类以运行该类中的所有测试方法。
    【解决方案3】:

    在 Github 中查看类似的问题,其中 answer/workaround 是在构造函数中使用一些注入和反射。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 2018-07-16
      • 2015-11-20
      • 2018-01-12
      • 2017-01-27
      • 1970-01-01
      相关资源
      最近更新 更多