[Fact(DisplayName = "Test Demo Display Name")]
[Trait("Category", "Internal")]
[Trait("Category", "All")]
public void Demo()
{
// I like to get the DisplayName 'Test Demo Display Name' here(inside this function) for furthur processing.
}
我想在此处(内部函数)获取DisplayName'Test Demo Display Name'进行进一步处理。怎么做?我知道有一些使用TraitsHelper类获取Traits详细信息的选项。事实属性是否也有类似的方法。
我不确定xUnit是否具有某种特定的机制来帮助您完成此操作,但是您可以轻松编写自己的帮助程序来进行此操作。
using System.Diagnostics;
using System.Linq;
static class XUnitHelper
{
internal static string FactDisplayName()
{
var frame = new StackFrame(1, true);
var method = frame.GetMethod();
var attribute = method.GetCustomAttributes(typeof(Xunit.FactAttribute), true).First() as Xunit.FactAttribute;
return attribute.DisplayName;
}
}
在单元测试方法内部,调用XUnitHelper.FactDisplayName()
。当然,如果有任何嵌套,这将不起作用-例如,如果您在另一个方法中调用此帮助程序,该方法本身是由Fact
装饰的单元测试方法调用的。要处理这样的情况,您必须编写遍历堆栈的更复杂的代码(实际上,这就是1
传递给StackFrame
的构造函数的原因;我们希望跳过该堆栈的信息)助手方法本身)。