如何从单元内测试中获取单元测试名称?
我在BaseTestFixture类中有以下方法:
public string GetCallerMethodName()
{
var stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();
return methodBase.Name;
}
我的Test Fixture类继承自基类:
[TestFixture]
public class WhenRegisteringUser : BaseTestFixture
{
}
我有下面的系统测试:
[Test]
public void ShouldRegisterThenVerifyEmailThenSignInSuccessfully_WithValidUsersAndSites()
{
string testMethodName = this.GetCallerMethodName();
//
}
当我在Visual Studio中运行它时,它会按预期返回我的测试方法名。
当它由TeamCity运行时,返回的是_InvokeMethodFast()
,这似乎是TeamCity在运行时生成的供自己使用的方法。
那么如何在运行时获得测试方法的名称呢?
发布于 2015-11-24 21:39:11
在使用Visual Studio运行测试时,如果在测试类中添加TestContext property,就可以很容易地获得此信息。
[TestClass]
public class MyTestClass
{
public TestContext TestContext { get; set; }
[TestInitialize]
public void setup()
{
logger.Info(" SETUP " + TestContext.TestName);
// .... //
}
}
发布于 2012-03-12 20:20:38
如果你没有使用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";
发布于 2012-03-16 17:58:27
谢谢你们;我使用了一种组合的方法,所以它现在可以在所有环境中工作:
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";
}
}
https://stackoverflow.com/questions/9666562
复制相似问题