【问题标题】:test "handled exceptions" junit测试“处理的异常”junit
【发布时间】:2013-07-30 19:39:18
【问题描述】:

我有一个处理异常的方法:

public boolean exampleMethod(){

    try{
      Integer temp=null;
      temp.equals(null);
      return
      }catch(Exception e){
        e.printStackTrace();
      }
    }

我想测试一下

public void test_exampleMethod(){}

我试过了

@Rule
public ExpectedException expectedException=ExpectedException.none();

public void test_exampleMethod(){
    expectedException.expect(JsonParseException.class);
    exampleMethod();
}

但这不起作用,因为异常是在内部处理的。

我也试过了

@Test(expected=JsonParseException.class)

但同样的问题...处理了异常

我知道我能做到

assertTrue(if(exampleMethod()))

但它仍会将堆栈跟踪打印到日志中。我更喜欢干净的日志...有什么建议吗?

【问题讨论】:

  • 你的例子不完整,你需要在你的方法的最后一个return语句

标签: exception junit


【解决方案1】:

你不能测试一个方法在内部做什么。这是完全隐藏的(除非有副作用,在外面可见)。

测试可以检查对于特定的输入,该方法返回预期的输出。但是您无法检查,这是如何完成的。因此,您无法检测是否有处理过的异常。

所以:要么不处理异常(让测试捕获异常),要么返回一个告诉您异常的特殊值。

无论如何,我希望你真正的异常处理比你的例子更明智。

【讨论】:

  • 谢谢。我希望有一种方法可以看到它们。唉,我将忍受肮脏的日志。是的,这些都是我能想到的“简单”的异常处理示例,而不是真正的代码。
【解决方案2】:

如果方法没有抛出异常,你就不能指望得到一个!

下面的例子是如何为抛出异常的方法编写一个 Junit 测试:

class Parser {
    public void parseValue(String number) {
        return Integer.parseInt(number);
    }
}

普通测试用例

public void testParseValueOK() {
    Parser parser = new Parser();
    assertTrue(23, parser.parseValue("23"));     
}

异常测试用例

public void testParseValueException() {
    Parser parser = new Parser();
    try {
       int value = parser.parseValue("notANumber");   
       fail("Expected a NumberFormatException");
    } catch (NumberFormatException ex) {
       // as expected got exception
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 2016-04-13
    • 1970-01-01
    • 2013-05-11
    • 2021-12-31
    • 1970-01-01
    • 2013-02-19
    相关资源
    最近更新 更多