運行失敗的JUnit 測試:重新運行解決方案
立即重新運行失敗的JUnit 測試可以增強自動化測試套件的穩定性,特別是在處理間歇性故障時。本文探討了實現這種機制的兩種方法。
1.使用 TestRule
TestRule 提供了一種靈活的方法來修改測試執行流程。若要使用 TestRule 實作重新運行,請定義:
<code class="java">public class Retry implements TestRule { private int retryCount; public Retry(int retryCount) { this.retryCount = retryCount; } public Statement apply(Statement base, Description description) { return statement(base, description); } private Statement statement(final Statement base, final Description description) { return new Statement() { @Override public void evaluate() throws Throwable { Throwable caughtThrowable = null; // Retry loop for (int i = 0; i < retryCount; i++) { try { base.evaluate(); return; } catch (Throwable t) { caughtThrowable = t; System.err.println(description.getDisplayName() + ": run " + (i+1) + " failed"); } } System.err.println(description.getDisplayName() + ": giving up after " + retryCount + " failures"); throw caughtThrowable; } }; } }
使用重試規則註解需要重試的測試:
<code class="java">@Rule public Retry retry = new Retry(3); @Test public void test1() { }
2。建立自訂 TestRunner
或者,可以定義自訂 TestRunner 來處理特定套件的測試重新運行。擴充BlockJUnit4ClassRunner 並重寫runChild() 方法:
<code class="java">public class CustomTestRunner extends BlockJUnit4ClassRunner { private int retryCount; public CustomTestRunner(Class<?> testClass) { super(testClass); } @Override protected void runChild(final FrameworkMethod method, RunNotifier notifier) { for (int i = 0; i < retryCount; i++) { try { super.runChild(method, notifier); return; } catch (Throwable t) { System.err.println(method.getName() + ": run " + (i+1) + " failed"); } } System.err.println(method.getName() + ": giving up after " + retryCount + " failures"); throw new RuntimeException(); } }</code>
將TestRunner 註解新增至套件類別:
<code class="java">@RunWith(CustomTestRunner.class) public class TestSuite { @BeforeClass public static void setUp() { ... } @AfterClass public static void tearDown() { ... } @Test public void test1() { ... } @Test public void test2() { ... } }</code>
兩種方法都允許靈活控制測試重新運行,提供靈活處理JUnit測試中間歇性故障的寶貴機制。
以上是如何為失敗的 JUnit 測試實現重新運行機制以提高測試套件的穩定性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!