[英]Get name of running test in Xunit
使用 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"));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.