如何使用 mockito 检查是否未引发异常?

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

我已经模拟了参数等,但是我不确定如何使用来测试该方法是否没有抛出异常?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?


}

答案 1

如果捕获到异常,则使测试失败。

@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");
   }
}

答案 2

如果您使用的是 5.2 或更高版本,则可以使用MockitoassertDoesNotThrow

Assertions.assertDoesNotThrow(() -> myClass.getBalanceForPerson(person1););

推荐