I am developing a desktop application, I want to test the method foo
of MyClass
and I have the following scenario:
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;
}
}
}
Then, I have MainWindow
with its static method 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
is the interface of my program, and jTextArea is the swing component that is printing the information that I send from MyClass.foo()
.
Now I am testing foo()
with jUnit, and I don't need the graphic user interface to test it. The test is pretty straight forward, but I get a nullPointer exception when calling the printing method because MainWindow
hasn´t been instantiated so jTextArea
is null.
My question is, is there any clean way of avoiding this error of being thrown?
I am using mockito and as far as I know, static methods cannot be mocked.
In some other cases, I could have done something like this:
MainWindow mainWindow = Mockito.mock(MainWindow.class);
But MainWindow
is not being set in MyClass
, so this is not very useful either.
Finally I came up with a workaround that does what I want, but it's not very clean. Basically I have declared a static boolean flag printText
and set it as false
at the very beginning of MainWindow
, and I am setting it as true in the class constructor. Then, in printInMain
I only print if this flag is true, which will only happen if this class has been previously instantiated.
This approach works but I was wondering whether there is a better solution than this, maybe using Mockito or some other mocking or testing techniques, as I am not very familiar with them.
I don't think this is a very good option because I am adding some code in the application just to make the test work, and the test should adapt to my code, not the code to my test.