Using Xunit, how can I get the name of the currently running test?
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); } }
Edit:
In particular, I am looking for a replacement for NUnits TestContext.CurrentContext.Test.Name
property.
Important note: xUnit.net uses the presence of the interface IClassFixture<> to know that you want a class fixture to be created and cleaned up. It will do this whether you take the instance of the class as a constructor argument or not.
Fact Attribute [Fact] attribute is used by the xUnit.net test runner to identify a 'normal' unit test - a test method that takes no method arguments.
About XUnit xUnit is a testing framework for . net languages (e.g. C#, F#, VB.NET) mostly focused in unit testing but that can also be used for integration testing. xUnit works with ReSharper, CodeRush, TestDriven.NET and Xamarin.
Besides the InlineData attribute, xUnit provides you with other ways to define data for theories, like ClassData , where the data source is a class implementing the IEnumerable interface, and MemberData , where the data source is a property or a method.
You can use BeforeAfterTestAttribute
to resolve your case. There are some ways to address your issue using Xunit, which would be to make sub-class of TestClassCommand, or FactAttribute and TestCommand, but I think that BeforeAfterTestAttribute
is the simplest way. Check out the code below.
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); } } }
See a similar question in Github where the answer/workaround is to use some injection and reflection in the constructor.
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); } <...> }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With