mercredi 23 décembre 2015

JUnit tests: How to check for errors with an try-catch block

So, I need to write a test for some (legacy) code I'm improving. In a method, I try to parse some string (which should be legal JSON). Then a possible JSONException is caught if the string doesn't represents valid JSON. Something like:

public void transformToJSON(String source) {
  try {
    JSONObject js = new JSONObject(new JSONTokener(item.getHtml()));
  }
  catch (JSONException e) {
    log(e)
  }
  //than js is added to an Hashset and the method is done
}

So I want to write a test for good input (to see if I have generated a correct JSON-object). This is 'easy' by checking the object in the Set.

For wrong input however, I need to find out if the correct error has been thrown. I know if an error was thrown in the code, I can check for it in the test.

  • By setting the rule public ExpectedException thrown= ExpectedException.none(); and checking for it in test method.
  • By adding @Test(expected = JSONException.class) above the test

But both wont work for try..catch blocks.

How can I test if the proper exception is caught by catch block? I want to change as little of the source code as possible.

Aucun commentaire:

Enregistrer un commentaire