获取Xunit中运行测试的名称
本文关键字:运行测试 Xunit 获取 | 更新日期: 2023-09-27 18:12:57
使用Xunit,我如何获得当前运行的测试的名称?
public class TestWithCommonSetupAndTearDown : IDisposable
{
public TestWithCommonSetupAndTearDown ()
{
var nameOfRunningTest = "TODO";
Console.WriteLine ("Setup for test '{0}.'", nameOfRunningTest);
}
[Fact]
public void Blub ()
{
}
public void Dispose ()
{
var nameOfRunningTest = "TODO";
Console.WriteLine ("TearDown for test '{0}.'", nameOfRunningTest);
}
}
编辑:
特别是,我正在寻找NUnits TestContext.CurrentContext.Test.Name
属性的替代品。
您可以使用BeforeAfterTestAttribute
来解决您的情况。有一些方法来解决你的问题使用Xunit,这将是使子类TestClassCommand,或FactAttribute和TestCommand,但我认为BeforeAfterTestAttribute
是最简单的方法。查看下面的代码:
public class TestWithCommonSetupAndTearDown
{
[Fact]
[DisplayTestMethodName]
public void Blub()
{
}
private class DisplayTestMethodNameAttribute : BeforeAfterTestAttribute
{
public override void Before(MethodInfo methodUnderTest)
{
var nameOfRunningTest = "TODO";
Console.WriteLine("Setup for test '{0}.'", methodUnderTest.Name);
}
public override void After(MethodInfo methodUnderTest)
{
var nameOfRunningTest = "TODO";
Console.WriteLine("TearDown for test '{0}.'", methodUnderTest.Name);
}
}
}
在Github中看到一个类似的问题,答案/解决方法是在构造函数中使用一些注入和反射。
public class Tests
{
public Tests(ITestOutputHelper output)
{
var type = output.GetType();
var testMember = type.GetField("test", BindingFlags.Instance | BindingFlags.NonPublic);
var test = (ITest)testMember.GetValue(output);
}
<...>
}
我不能和xUnit说话…但这确实为我在VS测试工作。也许值得一试。
参考:如何从代码
中获取当前方法的名称的例子:
[TestMethod]
public void TestGetMethod()
{
StackTrace st = new StackTrace();
StackFrame sf = st.GetFrame(0);
MethodBase currentMethodName = sf.GetMethod();
Assert.IsTrue(currentMethodName.ToString().Contains("TestGetMethod"));
}