尝试是这样的:
public class Base
{
public Base()
{
string methodName = this.GetType().GetMethods()
.Where(m => m.GetCustomAttributes<FactAttribute>().Any())
.Select(m => m.Name)
.FirstOrDefault();
Console.WriteLine("Test method name is " + methodName); // how to get test method name here.
}
}
编辑:
的xUnit有其试验前后运行属性挂钩的概念。 如果你想知道的方法的名称,当你运行它 - 你可以创建你的属性,它安慰这将输出:
public class MethodNameToConsoleAttribute : BeforeAfterTestAttribute
{
public override void Before(MethodInfo methodUnderTest)
{
Console.WriteLine("Test method name is " + methodUnderTest.Name);
}
}
,然后把它放在你的基类:
[MethodNameToConsole]
public class Base
{
...
}
编辑2:
好吧,现在我明白你想达到什么。 我必须说,目前xUnit不提供任何正常的方式来做到这一点。然而它有其他的概念叫做ITestOutputHelper
,它允许你将你的输出添加到xUnit的。在版本2中,xUnit团队只有一个此接口的实现,称为TestOutputHelper,它包含ITest类型的专用字段。
在这种特殊情况下,我们可以通过hack检索私有成员,然后从中检测方法名称。它应该是这样的:
public class Base
{
public Base(ITestOutputHelper testOutputHelper)
{
var helper = (TestOutputHelper)testOutputHelper;
ITest test = (ITest)helper.GetType().GetField("test", BindingFlags.NonPublic | BindingFlags.Instance)
.GetValue(helper);
testOutputHelper.WriteLine("Test method name is " + test.TestCase.TestMethod.Method.Name);
}
}
但我不建议你放下它,因为它的实施可能会改变未来的细节。
我宁愿在Github上创建一个问题,指定您需要的这种特殊情况。 xUnit是开源项目,您可以随时写信给开发人员。
你读过吗? http://stackoverflow.com/help/how-to-ask –