I'm new to Java, I want to write a JUnit test for a name validate class
I want to test the following code:
public boolean createNewUMLClassFromString(String className) {
if(validate(className)){
....
}
return false;
}
private boolean validate(String userInput){
/* check if it's empty */
if (userInput.equals("")){
JOptionPane.showMessageDialog(null, "Class Name can't be empty");
return false;
}
return true;
}
So I wrote a JUnit
public void emptyStringCheckerTest(){
assertFalse("new class can not be empty", um.createNewUMLClassFromString("do"));
}
it works, but in the test running process, I need to click the pop up dialog every time.
So Is anyone can tell me how to simulate a button click in the test process, or Is there a better way to write the test? Thanks?
To perform a programmatical button click, simply call the doClick()
method. I don't know how to insert that into your testing procedure, though.
Look at java.awt.Robot
, and at libraries like abbot
http://abbot.sourceforge.net/doc/overview.shtml that enhance it.
Rewrite your validate
method and move the JOptionPane
call to a separate method which you can replace in your unit test (e.g. a package visible method).
private boolean validate(String userInput){
/* check if it's empty */
if (userInput.equals("")){
showCannotBeEmptyDialog();
return false;
}
return true;
}
void showCannotBeEmptyDialog(){
JOptionPane.showMessageDialog(null, "Class Name can't be empty");
}
Making it package visible still allows you to override it in your test (e.g. to not show a UI), and you still will be capable of asserting whether that method was actually called.
Another option would be to pass an instance as a constructor parameter which would be responsible for showing messages to the user. In your production code, this instance would use the JOptionPane
class, where in your test you simply use a dummy. However, if it is just for showing one dialog this might be overkill.