有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JUnit测试:如何使用trycatch块检查错误

因此,我需要为我正在改进的一些(遗留)代码编写一个测试。在一个方法中,我尝试解析一些字符串(应该是合法的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对象)。通过检查集合中的对象,这很容易

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

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

但是这两种方法都不适用于try..catch

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


共 (5) 个答案

  1. # 2 楼答案

    使用格式错误的json字符串,然后在ur测试的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 
        }
    }
    
  2. # 3 楼答案

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

    但是,如果方法中有try/catch块,则无法查看是否发生异常,因为它是在方法中处理的。因此,您必须在方法中抛出异常,而不是捕获它,即

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

    然后检查是否发生异常

    或者,您可以返回一个布尔值,说明转换是否成功。然后,您可以测试返回值是否为真/假,以及这是否是您所期望的

    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"));
    }
    
  3. # 4 楼答案

    您的旧代码正在吞没异常。如果它抛出异常,那么您的junit@Test(expected=JSONException.class)将正常工作

  4. # 5 楼答案

    我会稍微修改一下代码,这样就可以了

    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