如何使用 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?

}

原文由 java123999 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.7k
2 个回答

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

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

原文由 UserF40 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您使用的是 Mockito 5.2 或更高版本,那么您可以使用 assertDoesNotThrow

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

原文由 user634545 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题