如何在unit testing中获取运行时的unit testing方法名称?

如何从单元内测试中获取unit testing名称?

我在BaseTestFixture类中有以下方法:

public string GetCallerMethodName() { var stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(1); MethodBase methodBase = stackFrame.GetMethod(); return methodBase.Name; } 

我的Test Fixture类inheritance自基类:

 [TestFixture] public class WhenRegisteringUser : BaseTestFixture { } 

我有以下系统测试:

 [Test] public void ShouldRegisterThenVerifyEmailThenSignInSuccessfully_WithValidUsersAndSites() { string testMethodName = this.GetCallerMethodName(); // } 

当我从Visual Studio中运行它时,它会按预期返回我的测试方法名称。

当这由TeamCity运行时,而是返回_InvokeMethodFast() ,这似乎是TeamCity在运行时为自己使用而生成的方法。

那么如何在运行时获取测试方法名称?

如果您使用的是NUnit 2.5.7 / 2.6 ,则可以使用TestContext类 :

 [Test] public void ShouldRegisterThenVerifyEmailThenSignInSuccessfully() { string testMethodName = TestContext.CurrentContext.Test.Name; } 

如果在测试类中添加TestContext属性 ,则使用Visual Studio运行测试时,可以轻松获取此信息。

 [TestClass] public class MyTestClass { public TestContext TestContext { get; set; } [TestInitialize] public void setup() { logger.Info(" SETUP " + TestContext.TestName); // .... // } } 

如果你没有使用NUnit,你可以遍历堆栈并找到测试方法:

 foreach(var stackFrame in stackTrace.GetFrames()) { MethodBase methodBase = stackFrame.GetMethod(); Object[] attributes = methodBase.GetCustomAttributes(typeof(TestAttribute), false); if (attributes.Length >= 1) { return methodBase.Name; } } return "Not called from a test method"; 

多谢你们; 我使用了一种组合方法,因此现在可以在所有环境中使用:

 public string GetTestMethodName() { try { // for when it runs via TeamCity return TestContext.CurrentContext.Test.Name; } catch { // for when it runs via Visual Studio locally var stackTrace = new StackTrace(); foreach (var stackFrame in stackTrace.GetFrames()) { MethodBase methodBase = stackFrame.GetMethod(); Object[] attributes = methodBase.GetCustomAttributes( typeof(TestAttribute), false); if (attributes.Length >= 1) { return methodBase.Name; } } return "Not called from a test method"; } } 

如果您不使用Nunit或任何其他第三方工具。 你不会得到TestAttribute

所以你可以这样做以获得测试方法名称。 使用TestAttribute的 TestMethodAttribute

  public string GetTestMethodName() { // for when it runs via Visual Studio locally var stackTrace = new StackTrace(); foreach (var stackFrame in stackTrace.GetFrames()) { MethodBase methodBase = stackFrame.GetMethod(); Object[] attributes = methodBase.GetCustomAttributes(typeof(TestMethodAttribute), false); if (attributes.Length >= 1) { return methodBase.Name; } } return "Not called from a test method"; }