簡體   English   中英

測試手冊停止后如何執行邏輯?

[英]How to execute logic after the test manual stop?

我正在編寫集成測試,該測試將在工作期間啟動多個服務器。 我需要確保在任何可能的情況下(包括使用IDE的手動測試停止)在測試后將它們關閉。 有沒有辦法做到這一點?

通過注冊一個Shutdown Hook,您可以涵蓋幾乎所有停止/停止方案:

Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
        System.out.println("Gracefully shutting down the application/test");
    }
});

但是,如果有人發出kill -9 ,那么甚至連shutdownHook都不會捕獲,因為此信號由操作系統處理,該操作系統殺死/中止了進程,甚至沒有將控件再次發送給它。

一個不錯的選擇是在自定義JUnit運行器中使用關閉鈎子,例如:

import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;

public class MyRunner extends BlockJUnit4ClassRunner {

    public MyRunner(Class<?> klass) throws InitializationError {
        super(klass);

        Runtime.getRuntime().addShutdownHook(new Thread("app-shutdown-hook") {
            @Override
            public void run() {
                // Your code here
                System.out.println("End of test");
            }
        });
    }

}

然后,使用此運行程序運行測試:

@RunWith(MyRunner.class)
public class MyTest {

    @Test
    public void test() {
        System.out.println("My test");
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM