[英]How to get xunit test method name in base class even before the control goes to the method?
我想在基类中找到测试方法的名称。
这是我的用例
public class TestClass : Base
{
[Fact]
public void TestMehthod()
{
}
}
public class Base
{
public Base()
{
Console.WriteLine("Test method name is "+); // how to get test method name here.
}
}
尝试这样的事情:
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类型的私有字段。
在这种特殊情况下,我们可以进行黑客攻击以检索私有成员,然后从中测试方法名称。 它看起来像这样:
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是一个开源项目,您可以随时向其开发人员写信。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.