首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在运行时从单元测试中获取单元测试方法名称?

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

Stack Overflow用户
提问于 2012-03-12 19:55:43
回答 3查看 22.3K关注 0票数 28

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

我在BaseTestFixture类中有以下方法:

代码语言:javascript
复制
public string GetCallerMethodName()
{
    var stackTrace = new StackTrace();
    StackFrame stackFrame = stackTrace.GetFrame(1);
    MethodBase methodBase = stackFrame.GetMethod();
    return methodBase.Name;
}

我的Test Fixture类继承自基类:

代码语言:javascript
复制
[TestFixture]
public class WhenRegisteringUser : BaseTestFixture
{
}

我有下面的系统测试:

代码语言:javascript
复制
[Test]
public void ShouldRegisterThenVerifyEmailThenSignInSuccessfully_WithValidUsersAndSites()
{
    string testMethodName = this.GetCallerMethodName();
    //
}

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

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

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

EN

回答 3

Stack Overflow用户

发布于 2015-11-24 21:39:11

在使用Visual Studio运行测试时,如果在测试类中添加TestContext property,就可以很容易地获得此信息。

代码语言:javascript
复制
[TestClass]
public class MyTestClass
{
    public TestContext TestContext { get; set; }

    [TestInitialize]
    public void setup()
    {
        logger.Info(" SETUP " + TestContext.TestName);
        // .... //
    }
}
票数 18
EN

Stack Overflow用户

发布于 2012-03-12 20:20:38

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

代码语言:javascript
复制
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";
票数 7
EN

Stack Overflow用户

发布于 2012-03-16 17:58:27

谢谢你们;我使用了一种组合的方法,所以它现在可以在所有环境中工作:

代码语言:javascript
复制
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";  
    }
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9666562

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档