我有一个简单的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?


}

最佳答案

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

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

10-06 05:45