2015-04-23 31 views
0

我負責爲各種情況下System.exit(1)所需的實用程序應用程序設置一些JUnit測試,並且System Rules非常適合測試。該應用程序也可以在GUI模式下運行,並彈出一個小的JFrame。當它在應用ExpectedSystemExit規則的JUnit測試環境中運行時,隨着JFrame的構建,一些祕密地退出jvm。關閉ExpectedSystemExit規則,然後測試運行,彈出JFrame就好了,只是我不能再測試jvm exit()。使用系統規則攔截System.exit()失敗,出現Swing窗口

一個猜測是SecurityManager系統規則1.9.0放置就是不允許某些權限。我仍在收集更多調試信息。在那之前,有沒有已知的解決方案這個問題?

+1

您是否在調用'setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)'?它調用SystemManager解釋爲'exit()'的'SecurityManager.checkExit'。 –

+0

@Banthar確實,進一步的調試顯示'setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)'觸發exit()。那麼現在怎麼辦? –

回答

0

setDefaultCloseOperation調用SecurityManager.checkExit來驗證exit可以被調用。系統規則基於SecurityManager,並將其解釋爲致電exit。這將會導致你的測試失敗,並且不可能構建你的awt窗口。

您必須創建您的窗口並在ExpectedSystemExit寄存器SecurityManager之前調用setDefaultCloseOperation。例如在@BeforeClass方法中:

@Rule 
public ExpectedSystemExit exit = ExpectedSystemExit.none(); 

static JFrame frame; 

@BeforeClass 
public static void before() { 
    frame = new JFrame(); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 
} 

@Test 
public void test() { 
    exit.expectSystemExitWithStatus(0); 
    frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING)); 
} 
+0

這將需要更改應用程序,以便在構建JFrame之後進行掛接。我希望有一個原位解決方案。 –

+0

您可以編寫自定義'SecurityManager',它將在從'setDefaultCloseOperation'調用時執行不同的操作。 –