Jul*_*ner 15 .net c# tdd 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);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
特别是,我正在寻找NUnits TestContext.CurrentContext.Test.Name
属性的替代品.
Jin*_*ung 13
您可以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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在 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);
}
<...>
}
Run Code Online (Sandbox Code Playgroud)