我開發一個桌面應用程序,我想測試方法的MyClass
foo
,我有以下情形:
MyClass的:替代嘲笑一個靜態方法
import package.MainWindow;
public class MyClass{
public int foo(){
//some logic
// . . .
boolean result = getResult();
if (result) {
MainWindow.printInMain("Success");
return 1;
} else {
MainWindow.printInMain("Fail: " + getCommentsAsString());
return 2;
}
}
}
然後,我有MainWindow
其靜態方法printInMain
:
public class MainWindow{
private static JTextArea jTextArea;
MainWindow(){
jTextArea = new JTextArea();
}
public static void printInMain(String string) {
jTextArea.append(string + "\n");
try {
jTextArea.setCaretPosition(jTextArea.
getLineStartOffset(jTextArea.getLineCount() - 1));
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
MainWindow
是我的程序的界面,並且JTextArea是一個被打印信息的Swing組件我從MyClass.foo()
發送。
現在我正在用jUnit測試foo()
,我不需要圖形用戶界面來測試它。該測試非常簡單,但在調用打印方法時會出現nullPointer異常,因爲MainWindow
尚未實例化,所以jTextArea
爲空。
我的問題是,有避免被拋出這個錯誤的任何干淨的方法?
我使用mockito,據我所知,static methods cannot be mocked。
在其他一些情況下,我可以做這樣的事情:
MainWindow mainWindow = Mockito.mock(MainWindow.class);
但MainWindow
不MyClass
被設置,所以這一點無論是不是很有用。
最後我想出了一個解決方法,它可以做我想做的事情,但它不是很乾淨。基本上我已經聲明瞭一個靜態布爾標誌printText
,並在MainWindow
的最開始處將它設置爲false
,並且在類構造函數中將其設置爲true。然後,在printInMain
中,只有在此標誌爲真時纔會打印,只有當此類先前已實例化時纔會發生。
這種方法的工作原理,但我想知道是否有比這更好的解決方案,也許使用Mockito或其他一些模擬或測試技術,因爲我不是很熟悉它們。
我不認爲這是一個很好的選擇,因爲我在應用程序中添加了一些代碼,只是爲了使測試工作,測試應該適應我的代碼,而不是我的測試代碼。
感謝您的答案Brett。我雖然關於這個空指針檢查,當我寫完問題時,我可能會添加它。關於'jTextArea'是非靜態的,問題是很多類只調用主窗口的這個方法,並且只有一個主窗口,所以使它非靜態意味着我必須通過' MainWindow「給每一個我想讓它打印的課程,對嗎? – Juan
小心使用Singleton模式可能有助於避免傳遞'MainWindow'對象。 –