Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress JOptionPane.showInputDialog in junit test

Tags:

junit

I am using the JOptionPane.showInputDialog call in my code. When the junit tests run it pops up the window. Is there a way to suppress the pop-up? Wold mocking it help? Please help me on this.

like image 240
Alex Avatar asked Oct 30 '12 14:10

Alex


1 Answers

I know - this question is ancient. But maybe sometimes someone will have the same problem...

Remember: It's your code, isn't it? So you can easily refactor from

 public boolean myMethod() {
  String value = "NOTHING";
  if(this.someCondition) {
    value = JOptionPane.showInputDialog(...);
  }
  return "NOTHING".equals(value);
 }

to

public boolean myMethod() {
  String value = "NOTHING";
  if(this.someCondition) {
     value = getValueFromDialog();
  }
  return "NOTHING".equals(value);
}

protected getValueFromDialog() {
  return JOptionPane.showInputDialog(...)
}

This done, you can write a test mocking away the actual invocation of JOptionPane (Example uses Mockito syntax)

@Test
public void test_myMethod() {
    MyClass toTest = mock(MyClass.class);

    //Call real method we want to test     
    when(toTest.myMethod()).doCallRealMethod();

    //Mock away JOptionPane
    when(toTest.getValueFromDialog()).thenReturn("HELLO JUNIT");

    //Perform actual test code
    assertFalse(toTest.myMethod());
}

All done - now add tests simulating all the funny stuff that might happen as a result of JOptionPane.showInputDialog() (returning null, returning unexpected values...) by simply adding test cases and different values for

when(toTest.getValueFromDialog()).thenReturn(...);
like image 177
Jan Avatar answered Sep 22 '22 15:09

Jan