如何从单元测试中获得在运行单元测试方法的名字吗? [英] How to get the unit test method name at runtime from within the unit test?
问题描述
如何从单元测试中获得的单元测试的名字吗?
How to get the unit test name from the within unit test?
我有一个BaseTestFixture类里面的方法如下:
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
{
}
和我有以下系统测试:
[Test]
public void ShouldRegisterThenVerifyEmailThenSignInSuccessfully_WithValidUsersAndSites()
{
string testMethodName = this.GetCallerMethodName();
//
}
当我运行这个从Visual Studio中,它返回预期我的测试方法的名称。
When I run this from within the Visual Studio, it returns my test method name as expected.
在此运行由TeamCity的,而不是 _InvokeMethodFast()
返回这似乎是TeamCity的生成在运行时供自己使用的方法。
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?
推荐答案
如果您正在使用的 NUnit的2.5.7 / 2.6 您可以使用的的TestContext类:
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;
}
这篇关于如何从单元测试中获得在运行单元测试方法的名字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!