【问题标题】:How to get the parent method name?如何获取父方法名称?
【发布时间】:2012-10-25 14:22:49
【问题描述】:

我正在使用 NUnit 和 Selenium WebDriver 编写 Web 测试。 在每次测试结束时,我想获取浏览器的屏幕截图并保存图像。 我希望图像名称与Test 名称相同。 但我无法获取测试方法名称。

这是测试方法:

[Test]
public void AbcTest_ShouldPass()
{
    Assert.AreEqual(true, true);
}

这是在每个Test 之后运行的TearDown

[TearDonw]
[MethodImpl(MethoImplOptions.NoInlining)]
public void TestCleanupNunit()
{
    var methodName = new List<string>();
    for (int i = 0; i < 30; i++)
        methodName.Add(i.ToString() + " is " + new StackTrace(i, true).GetFrame(0).GetMethod().Name);

}

但是当我查看methodName 时,我找不到AbcTest_ShouldPass

0 is TestCleanupNUnit
1 is InvokeMethod
2 is UnsafeInvokeInternal
3 is Invoke
4 is Invoke
5 is InvokeMethod
6 is InvokeMethod
7 is RunTearDown
8 is RunTest
9 is RunTest
10 is RunRepeatedTest
11 is RunTestInContext
12 is Run
13 is RunAllTests
14 is RunSuite
15 is RunSuiteInContext
16 is Run
17 is Run
18 is RunAllTests
19 is RunSuite
20 is RunSuiteInContext
21 is Run
22 is RunAllTests
23 is RunSuite
24 is RunSuiteInContext
25 is Run
26 is RunAllTests
27 is RunSuite
28 is RunSuiteInContext
29 is Run

我查看了这个post,但对我没有帮助。

【问题讨论】:

    标签: c# reflection nunit


    【解决方案1】:

    Nunit 框架提供 CurrentContext,它是 NUnit.Framework.TestContext 的成员。

    TestContext.CurrentContext.Test.Name 将返回正在执行的测试的名称,而 TestContext.CurrentContext.Test.FullName 将返回从命名空间名称开始的完全限定名称。

    【讨论】:

      【解决方案2】:

      是的,因为您的测试不会调用测试拆解。测试运行程序调用您的测试用例,然后依次关闭测试。换句话说,您的测试用例方法调用与拆解位于堆栈跟踪的不同分支中。

      您需要将您的方法名称缓存在您的测试夹具中的某个地方。也许是一个私有成员变量,您在每个测试用例的方法中设置该变量。这不是很优雅,但这是我目前能想到的唯一方法。

      【讨论】:

      • 这和我之前做的差不多。我希望有更好的方法。但感谢您提供更多信息。
      【解决方案3】:

      不幸的是,单元测试的 Setup 和 Teardown 方法不作为同步调用堆栈的一部分运行,而是由测试引擎处理。因此,从 Teardown 方法观察到的调用堆栈将不包含作为测试的一部分运行的方法。

      【讨论】:

        【解决方案4】:

        您可以只使用一个私有方法来保存您在每次测试结束时调用的屏幕截图,而不是将其包含在测试中。然后您的堆栈跟踪将包含您所期望的测试用例方法。

        我同意这种方法并不完美,因为您必须记住将其添加到每个测试用例中,但至少它是通用的并且不涉及硬编码字符串中的方法名称。

        【讨论】:

          猜你喜欢
          • 2012-03-27
          • 1970-01-01
          • 2011-01-17
          • 2013-07-07
          • 1970-01-01
          • 2010-09-18
          • 2014-03-06
          • 2015-03-08
          • 1970-01-01
          相关资源
          最近更新 更多