如何在事实测试方法中获取 xUnit 事实属性'DisplayName'参数



[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.
}

我喜欢在这里(函数内部(获取显示名称"测试演示显示名称"以进行进一步处理。怎么做? 我知道有一些选项可以使用TraitsHelper类获取特征详细信息。是否有任何类似的方法可用于事实属性。

我不确定 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的构造函数;我们希望跳过帮助程序方法本身的堆栈信息(。

最新更新