Java:如何測試調用System.exit()的方法?我有一些方法可以調用System.exit()某些輸入。不幸的是,測試這些情況會導致JUnit終止!將方法調用放在新線程中似乎沒有幫助,因為System.exit()終止JVM,而不僅僅是當前線程。是否有任何常見的處理方式?例如,我可以替換存根System.exit()嗎?[編輯]有問題的類實際上是一個命令行工具,我試圖在JUnit中測試。也許JUnit根本不適合這份工作?建議使用補充回歸測試工具(最好是與JUnit和EclEmma完美集成的東西)。
3 回答

qq_遁去的一_1
TA貢獻1725條經驗 獲得超8個贊
庫系統規則庫有一個名為ExpectedSystemExit的JUnit規則。使用此規則,您可以測試調用System.exit(...)的代碼:
public void MyTest { @Rule public final ExpectedSystemExit exit = ExpectedSystemExit.none(); @Test public void systemExitWithArbitraryStatusCode() { exit.expectSystemExit(); //the code under test, which calls System.exit(...); } @Test public void systemExitWithSelectedStatusCode0() { exit.expectSystemExitWithStatus(0); //the code under test, which calls System.exit(0); }}
完全披露:我是該圖書館的作者。

牧羊人nacy
TA貢獻1862條經驗 獲得超7個贊
實際上,您可以System.exit
在JUnit測試中模擬或刪除該方法。
例如,您可以使用JMockit編寫(還有其他方法):
@Testpublic void mockSystemExit(@Mocked("exit") System mockSystem){ // Called by code under test: System.exit(); // will not exit the program}
編輯:替代測試(使用最新的JMockit API),在調用之后不允許任何代碼運行System.exit(n)
:
@Test(expected = EOFException.class)public void checkingForSystemExitWhileNotAllowingCodeToContinueToRun() { new Expectations(System.class) {{ System.exit(anyInt); result = new EOFException(); }}; // From the code under test: System.exit(1); System.out.println("This will never run (and not exit either)");}
添加回答
舉報
0/150
提交
取消