简体   繁体   中英

JUnit expected exception not working as expected

i am trying to test a private method inside an ActionListener. The method should throw an exception if an invalid url is passed: Heres the code of my test:

@Rule
public ExpectedException expectedException = ExpectedException.none();
Map<JLabel, JTextField> inputs;
ActionListener listener;
AddStationWindow window;
ArrayList<Station> stationsToDelete;

@Before
public void setUp() throws IllegalAccessException, NoSuchFieldException, 
InstantiationException, SQLException, ClassNotFoundException {
inputs = new HashMap<JLabel, JTextField>();
window = new AddStationWindow();
stationsToDelete = new ArrayList<>();
InitializeH2Database.initialiteDatabase();

}

@Test
public void saveStation() throws NoSuchFieldException, 
IllegalAccessException, MalformedURLException, NoSuchMethodException, 
InvocationTargetException {
  Field f = window.getClass().getDeclaredField("inputElements");
  f.setAccessible(true);
  LinkedHashMap<JLabel, JTextField> inputs = (LinkedHashMap<JLabel, 
  JTextField>) f.get(window);
  Field f2 = window.getClass().getDeclaredField("save");
  f2.setAccessible(true);
  JButton saveButton = (JButton) f2.get(window);
  inputs.get(window.getInputLabels().get(0)).setText("Testsender");
  inputs.get((window.getInputLabels().get(1))).setText("asdasdsa");
  ActionListener listener = saveButton.getActionListeners()[0];
  Method m = listener.getClass().getDeclaredMethod("saveStation");
  m.setAccessible(true);
  m.invoke(listener);
  expectedException.expect(MalformedURLException.class);
}


@After
public void tearDown() {
stationsToDelete.forEach(s -> 
H2DatabaseConnector.getInstance().deleteStation(s));
}

This is the tested method inside the ActionListener:

private boolean saveStation() {
List<JLabel> keys = new ArrayList<>();
for (Map.Entry<JLabel, JTextField> inputElement : inputElements.entrySet()) {
    keys.add(inputElement.getKey());
}
String stationName = inputElements.get(keys.get(0)).getText();
String urlString = inputElements.get(keys.get(1)).getText();
URL stationURL = null;
try {
    stationURL = new URL(urlString);
} catch (MalformedURLException e) {
    JOptionPane.showMessageDialog(window, "Invalid URL!", "URL 
    not valid", JOptionPane.ERROR_MESSAGE);
    e.printStackTrace();
    return false;
}
Station s = new Station(stationName, stationURL);
if (checkStation(s)) {
    return WebradioPlayer.addStation(s);
}
return false;
}

If i run the test, i can see that the stack tarce shows the malformed url exception with message no protocol: 'asdasdsa', but the test fails. Can someone explain me why? JUnit version is 4.

You have to set the expected exception before you call the code that actually does throw the exception.

Instead of

@Test
public void saveStation() throws ... {
    // code here
    expectedException.expect(MalformedURLException.class);
}

you should write the test method as

@Test
public void saveStation() throws ... {
    expectedException.expect(MalformedURLException.class);
    // code here
}

Additionally, you have to change your method saveStation to not suppress the exception if you actually want to have it thrown. See @Leviand's answer for more details.

Your test is failing because you are expecting an exception to be thrown (you said invalid url exception), but you are wrapping that exception into a try catch, then you are printing the stacktrace.

try {
    stationURL = new URL(urlString);
} catch (MalformedURLException e) {
    JOptionPane.showMessageDialog(window, "Invalid URL!", "URL 
    not valid", JOptionPane.ERROR_MESSAGE);
    e.printStackTrace();
    return false;
}

you have to add the trown declaration in your catch, or not catch it at all, ie:

} catch (MalformedURLException e) {
    JOptionPane.showMessageDialog(window, "Invalid URL!", "URL 
    not valid", JOptionPane.ERROR_MESSAGE);
    e.printStackTrace();
    throw new MalformedURLException(e);
}

and add the throw info to your method

private boolean saveStation() throws MalformedURLException{

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM