[英]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.