测试“处理例外” JUnit的 [英] test "handled exceptions" junit

查看:221
本文介绍了测试“处理例外” JUnit的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public boolean exampleMethod(){

尝试{
整数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()))

但它仍然会将堆栈跟踪打印到日志中。我更喜欢干净的日志...任何建议?

解决方案

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



测试可以检查特定的输入方法返回预期的输出。但你不能检查,这是如何做的。所以你没有办法检测是否有一个你已经处理的异常。



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



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


I have a method with a handled exception:

public boolean exampleMethod(){

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

I want to test it

public void test_exampleMethod(){}

I have tried

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

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

but that doesnt work because the exception is handled inside.

I also tried

@Test(expected=JsonParseException.class)

but same issue...the exception is handled

I know that I can just do

assertTrue(if(exampleMethod()))

but it will still print the stack trace to the log. I would prefer clean logs...Any suggestions?

解决方案

You cannot test what a method is doing internally. This is completely hidden (unless there are side effects, that are visible outside).

The test can check that for a specific input the method returns a expected output. But you can not check, how this is done. So you have no way to detect if there was a exception that you have handled.

So: either don't handle the exception (let the test catch the exception), or return a special value that tells you about the exception.

Anyway, I hope your real exception handling is more sensible than in your example.

这篇关于测试“处理例外” JUnit的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆