I have made a game where a user and an AI takes turns "rolling" a dice. The game automatically takes the AI's turn and returns to the user's turn. I used JOptionPane.showMessageDialog to popup a dialog box notifying the user that it is their turn. So all this is working properly but when I execute a JUnit test class to test the hold() method the popup comes up. Is there a way to suppress the popup or automatically close the window in a JUnit Test class?
public void hold() {
this.swapWhoseTurn();
this.setChanged();
this.notifyObservers();
if (this.getCurrentPlayer().getIsMyTurn() == this.getComputerPlayer().getIsMyTurn()) {
this.theComputer.takeTurn();
this.hold();
HumanPlayerPanel.turnAlert();
}
The turnAlert is a static method in another class called HumanPlayerPanel. Here is the code.
public static void turnAlert() {
JOptionPane.showMessageDialog(null, "It is your turn");
}
I saw that I can call doClick method on the OK_Option button but I'm not too sure how to find that button. Any help is appreciated.
Refactor if statement as follows:
if (this.getCurrentPlayer().getIsMyTurn() == this.getComputerPlayer().getIsMyTurn()) {
this.theComputer.takeTurn();
this.hold();
HumanPlayerPanel.turnAlert();
}
to look like this:
...
if (this.getCurrentPlayer().getIsMyTurn() == this.getComputerPlayer().getIsMyTurn()) {
this.theComputer.takeTurn();
this.hold();
alertHumanPlayer();
}
...
protected void alertHumanPlayer(){
HumanPlayerPanel.turnAlert();
}
Let's assume above class is called Game. In your test code, extend Game class as follows:
...
public class GameWithNoHumanAlert extends Game{
@Override
protected void alertHumanPlayer(){
// Do not show alert
// HumanPlayerPanel.turnAlert();
}
}
@Test
public void uiTest(){
GameWithNoHumanAlert game = new GameWithNoHumanAlert();
...
// Do your testing normally now.
}
__UPDATE__
Another, and IMHO a better, idea would be to use mock testing. I have personally tried several of them and I an suggest you to take a look at Jmockit. It is almost trivial to deal with this kind of troubles with it so that you can focus on what you want to / need to test.
Cheers.