'How to get xunit test method name in base class even before the control goes to the method?
I want to find the test method name in the base class.
Here is my use case
public class TestClass : Base
{
[Fact]
public void TestMehthod()
{
}
}
public class Base
{
public Base()
{
Console.WriteLine("Test method name is "+); // how to get test method name here.
}
}
Solution 1:[1]
Creating a Xunit Test class Constructor, and injecting it with an ITestOutputHelper could help you extract the test method name before the code run. Weirdly looking at first, this test class constructor would run on before each test method and you can use it to prepare your assets and also to use the test output if you inject the ITestOutputHelper (No other registration needed).
On your test class constructor, you can do something like that add the test method name as a class member (It will be new for each test method...)
On other note Console.Writeline() would not work in Xuint context, but you can use the same helper weve injected for that!
public class TestClass : Base
{
public TestClass(ITestOutputHelper helper):Base(helper)
{
}
}
...
public class Base
{
public Base(ITestOutputHelper helper)
{
var type = helper.GetType();
var testMember = type.GetField("test", BindingFlags.Instance | BindingFlags.NonPublic);
var testMethodName = ((ITest)testMember.GetValue(helper)).DisplayName;
helper.WriteLine("Test method name is "+testMethodName);
//
}
}
If you need the test method in more then one place, you can create an ITestOutputHelper Extension method and use it on the object it self:
public static string GetTestName(this ITestOutputHelper helper)
{
var type = helper.GetType();
var testMember = type.GetField("test", BindingFlags.Instance | BindingFlags.NonPublic);
return ((ITest)testMember.GetValue(helper)).DisplayName;
}
And then call the helper.GetTestName()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gezman |
