如何在单元测试中从运行时获取单元测试方法名称?

The*_*ght 22 c# teamcity automated-tests unit-testing

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

我在BaseTestFixture类中有以下方法:

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

我的Test Fixture类继承自基类:

[TestFixture]
public class WhenRegisteringUser : BaseTestFixture
{
}
Run Code Online (Sandbox Code Playgroud)

我有以下系统测试:

[Test]
public void ShouldRegisterThenVerifyEmailThenSignInSuccessfully_WithValidUsersAndSites()
{
    string testMethodName = this.GetCallerMethodName();
    //
}
Run Code Online (Sandbox Code Playgroud)

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

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

那么我怎样才能在运行时获得测试方法名称?

nem*_*esv 19

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

[Test]
public void ShouldRegisterThenVerifyEmailThenSignInSuccessfully()
{
    string testMethodName = TestContext.CurrentContext.Test.Name;
}
Run Code Online (Sandbox Code Playgroud)

  • MSTest也在其TestContext中公开此信息 (2认同)

小智 18

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

[TestClass]
public class MyTestClass
{
    public TestContext TestContext { get; set; }

    [TestInitialize]
    public void setup()
    {
        logger.Info(" SETUP " + TestContext.TestName);
        // .... //
    }
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*mlk 7

如果您不使用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";
Run Code Online (Sandbox Code Playgroud)


The*_*ght 7

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

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";  
    }
}
Run Code Online (Sandbox Code Playgroud)