【问题标题】:How can I get access to the current test method in NUnit如何访问 NUnit 中的当前测试方法
【发布时间】:2022-01-05 05:41:22
【问题描述】:

TestContext.CurrentContext.Test 有几个属性,如 FullName,可以解析这些属性以获取 NUnit 中的当前测试方法。但是,当使用 TestCase 属性上的 TestName 属性覆盖测试名称时,这些都没有帮助。

有没有一种简单的方法可以从 NUnit 测试中获取当前测试方法的 MethodInfo?我不能简单地使用堆栈跟踪,因为当测试方法不在堆栈上时,我需要在 SetUp 和 TearDown 中提供这些信息。

我正在使用 NUnit 2.6.2

【问题讨论】:

    标签: nunit testcontext


    【解决方案1】:

    我想到的一件事是写custom NUnit EventListener addin

    然后您可以挂钩到测试运行程序的运行周期,并且至少在 TestStarted 重载时您将拥有 TestName 对象。这不会直接提供 MethodInfo,但您可以通过使用那里的给定属性来获得它。

    祝你好运!

    【讨论】:

    • 不幸的是,您发送的链接说 EventListeners 是异步调用的,因此不会影响测试。因此,似乎一旦我在测试中,我就无法使用此方法来获取当前的测试方法。
    • 在每个测试运行之前调用它。然后你可以存储你需要的信息——比如说在一个静态变量中——并在测试中使用它in
    【解决方案2】:

    默认情况下,NUnit 不提供此类信息 - 但它可以通过私有字段和属性进行查询。例如可以使用以下代码(使用 NUnit 3.13.2 测试):

        /// <summary>
        /// Accesses private class type via reflection.
        /// </summary>
        /// <param name="_o">input object</param>
        /// <param name="propertyPath">List of properties in one string, comma separated.</param>
        /// <returns>output object</returns>
        object getPrivate(object _o, string propertyPath)
        {
            object o = _o;
            var flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
            
            foreach (var name in propertyPath.Split('.'))
            {
                System.Type type = o.GetType();
    
                if (char.IsUpper(name[0]))
                    o = type.GetProperty(name, flags).GetValue(o);
                else
                    o = type.GetField(name, flags).GetValue(o);
            }
    
            return o;
        }
    
        [SetUp]
        public void EachSpecSetup()
        {
            var mi = (MemberInfo)getPrivate(TestContext.CurrentContext.Test, "_test.Method.MethodInfo");
            // Alternative method - using Exposed nuget package:
            //dynamic test = Exposed.From(TestContext.CurrentContext.Test)._test;
            //dynamic method = Exposed.From(test)._method;
            FactAttribute attr = mi.GetCustomAttribute<FactAttribute>();
            string path = attr.FilePath;
            string funcName = attr.FunctionName;
        }
    

    就像上面代码中提到的那样,也可以使用Exposed.From - 但主要示例理论上应该更快。

    如果任何字段/属性无效,代码将抛出异常 - 这是故意的 - 使用 Visual Studio 监视窗口来识别类型/字段/属性。

    【讨论】:

      猜你喜欢
      • 2011-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      • 1970-01-01
      相关资源
      最近更新 更多