我有一个处理异常的方法:
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)
但是处理相同的issue...the异常
我知道我可以
assertTrue(if(exampleMethod()))
但是它仍然会将堆栈跟踪打印到日志。我更喜欢干净的logs...Any建议?
发布于 2013-07-30 19:52:28
您不能在内部测试一个方法正在做什么。这是完全隐藏的(除非有副作用,在外面是可见的)。
测试可以检查对于特定输入,该方法是否返回预期的输出。但是你不能检查,这是怎么做的。因此,您无法检测是否存在您处理过的异常。
所以:要么不处理异常(让测试捕获异常),要么返回一个告诉您异常的特殊值。
无论如何,我希望您真正的异常处理比在您的示例中更明智。
发布于 2013-07-30 19:52:03
如果该方法不抛出异常,则不能期望得到异常!
下面是如何为抛出异常的方法编写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
}
}
https://stackoverflow.com/questions/17955899
复制相似问题