如何使用mockito检查是否没有抛出异常?

jav*_*999 13 java unit-testing exception-handling exception mockito

我有一个简单的Java方法,我想检查它不会抛出任何exceptions.

我已经模拟了参数等,但我不知道如何使用Mockito测试没有从方法抛出异常?

目前的测试代码:

  @Test
  public void testGetBalanceForPerson() {

   //creating mock person
   Person person1 = mock(Person.class);
   when(person1.getId()).thenReturn("mockedId");

  //calling method under test
  myClass.getBalanceForPerson(person1);

  //How to check that an exception isn't thrown?


}
Run Code Online (Sandbox Code Playgroud)

Use*_*F40 28

如果发现异常,则测试失败.

@Test
  public void testGetBalanceForPerson() {

   //creating mock person
   Person person1 = mock(Person.class);
   when(person1.getId()).thenReturn("mockedId");

  //calling method under test
   try{
        myClass.getBalanceForPerson(person1);

   }
   catch(Exception e){
      fail("Should not have thrown any exception");
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是捕获异常的旧方法。下面的答案应该是使用 JUnit 5.x 执行此操作的答案 (3认同)

use*_*545 10

如果您使用的是Mockito5.2 或更高版本,那么您可以使用 assertDoesNotThrow

Assertions.assertDoesNotThrow(() -> myClass.getBalanceForPerson(person1););
Run Code Online (Sandbox Code Playgroud)


小智 6

只要您没有明确说明,您期望异常,JUnit将自动失败任何抛出未捕获的异常的测试.

例如,以下测试将失败:

@Test
public void exampleTest(){
    throw new RuntimeException();
}
Run Code Online (Sandbox Code Playgroud)

如果您还想检查,测试将在Exception上失败,您只需在throw new RuntimeException();要测试的方法中添加一个,运行测试并检查它们是否失败.

当您没有手动捕获异常并且未通过测试时,JUnit将在失败消息中包含完整堆栈跟踪,这使您可以快速找到异常的来源.