JUnit测试:如何使用try-catch块检查错误

时间:2015-12-23 14:41:00

标签: java exception testing junit exception-handling

所以,我需要为我正在改进的一些(遗留)代码编写一个测试。在一个方法中,我尝试解析一些字符串(应该是合法的JSON)。如果字符串不表示有效的JSON,则会捕获可能的JSONException。类似的东西:

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
}

所以我想编写一个测试以获得良好的输入(看看我是否生成了正确的JSON对象)。通过检查Set中的对象,这很容易。

但是对于错误的输入,我需要找出是否抛出了正确的错误。 我知道如果代码中出现错误,我可以在测试中检查它。

  • 通过设置规则public ExpectedException thrown= ExpectedException.none();并在测试方法中检查它。
  • 在测试上方添加@Test(expected = JSONException.class)

但两者都不适用于try..catch块。

如何测试catch块是否捕获了正确的异常?我想尽可能少地更改源代码。

5 个答案:

答案 0 :(得分:2)

在JUnit测试类中,您可以在try或catch块中使用fail("this should not have happened"),具体取决于应该和不应该工作的内容(如:在JUnit类中尝试和捕获,而不是在您的实际方法中! )。

但是,使用方法中的try / catch块,您无法查看是否发生异常,因为它是在方法中处理的。所以你必须在方法中抛出异常而不是捕获它,即。,

public void transformToJSON(String source) throws JSONException { ... }

然后它将检查是否发生异常。

或者,您可以返回一个布尔值,指出转换是否成功。然后,您可以测试返回值是否为true / false,以及是否符合预期。

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

在您的测试课程中:

@Test
public void testTransformToJSON() {
      assertTrue(transformToJSON("whatever"));
}

答案 1 :(得分:2)

根据代码中使用的日志记录,您可以使用Mockito来验证catch块中记录的消息。

有关设置单元测试的更多详细信息,请通过以下链接

http://bloodredsun.com/2010/12/09/checking-logging-in-unit-tests/

答案 2 :(得分:0)

您的遗留代码正在吞噬异常。如果它抛出一个异常,那么你的junit @Test(expected = JSONException.class)就可以了。

答案 3 :(得分:0)

我稍微更改了代码,因此它是

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

public JSONObject getJSON(String source) throws JSONException {
  return new JSONObject(new JSONTokener(source));
}

然后针对getJSON进行测试。抛出异常,正如其他人所说(和你),你可以在测试类中使用expectedException

答案 4 :(得分:0)

使用格式错误的json字符串,然后在ur test的catch块中执行断言或其他操作。

@Test
public void shouldCatchException(){
    String source = "{ \"name\":\"John\", \"age\":30, \"car\":null ";
    try {
        jsonHelper.transformToJSON(source);
    }catch (JSONException e){
        Assert.assertThat(e, notNullValue());
        assertTrue(StringUtils.isNotBlank(e.getMessage());
        //whatever else u need to assert 
    }
}