0

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

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()))

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

4

2 回答 2

1

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

下面的示例如何为抛出异常的方法编写 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
    }
}
于 2013-07-30T19:52:03.087 回答
1

您无法测试方法在内部执行的操作。这是完全隐藏的(除非有副作用,在外面可见)。

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

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

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

于 2013-07-30T19:52:28.687 回答