jUnit测试用例应该在throws声明还是try catch块中处理默认异常

use*_*222 6 java junit exception

如果我为一个抛出一堆异常的函数编写测试用例,我应该在我的测试方法中为这些异常添加一个throws声明,还是应该捕获每个异常.这是怎样的正确方法?我相信try-catch是一种更好的方法,但是在catch块中我应该打印堆栈跟踪吗?

例如,我有一个getGroups(String name)抛出的方法AuthenticationException.如果我编写一个测试用例来检查IllegalArgumentExceptionname参数为null 时是否抛出了一个,我该如何处理AuthenticationException?我是否将它添加到抛出我方法的一部分,或者我应该将异常包含在一个try-catch块中.

@Test
public void testGetGroupsWithNull() throws AuthenticationException {
 thrown.expect(IllegalArgumentException.class);
 getGroups(null);
}
Run Code Online (Sandbox Code Playgroud)

在上面的测试用例中我刚添加了一个throws AuthenticationException,但是我想知道是否最好将异常包含在try-catch块中以及在捕获异常后我做了什么.我可以打印堆栈跟踪.

AuthenticationException通过不将它放在'throws'子句中而是放在try/catch块中来处理意外异常.

@Test
public void testGetGroupsWithNull() {
thrown.expect(IllegalArgumentException.class);
try {
  getGroups(null);
} catch(AuthenticationExcption e) {
  Assert.fail("Authentication Exception");
}
}
Run Code Online (Sandbox Code Playgroud)

Jim*_*ows 5

JUnit在这里有一篇很棒的文章:https://github.com/junit-team/junit/wiki/Exception-testing this subject.你可以做:

@Test(expected= IndexOutOfBoundsException.class) 
public void empty() { 
  new ArrayList<Object>().get(0); 
}
Run Code Online (Sandbox Code Playgroud)

要么:

@Test
  public void testExceptionMessage() {
      try {
          new ArrayList<Object>().get(0);
          fail("Expected an IndexOutOfBoundsException to be thrown");
      } catch (IndexOutOfBoundsException anIndexOutOfBoundsException) {
          assertThat(anIndexOutOfBoundsException.getMessage(), is("Index: 0, Size: 0"));
      }
  }
Run Code Online (Sandbox Code Playgroud)