How to get the unit test method name at runtime from within the unit test?

The Light picture The Light · Mar 12, 2012 · Viewed 20.2k times · Source

How to get the unit test name from the within unit test?

I have the below method inside a BaseTestFixture Class:

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

My Test Fixture class inherits from the base one:

[TestFixture]
public class WhenRegisteringUser : BaseTestFixture
{
}

and I have the below system test:

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

When I run this from within the Visual Studio, it returns my test method name as expected.

When this runs by TeamCity, instead _InvokeMethodFast() is returned which seems to be a method that TeamCity generates at runtime for its own use.

So how could I get the test method name at runtime?

Answer

nemesv picture nemesv · Mar 12, 2012

If you are using NUnit 2.5.7 / 2.6 you can use the TestContext class:

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