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

标签 java unit-testing exception exception-handling mockito

我有一个简单的Java 方法,我想检查它是否不会抛出任何异常

我已经模拟了参数等,但是我不确定如何使用 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");
   }
}

关于java - 如何使用 mockito 检查是否没有抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38868620/

相关文章:

java - 如何将用户定义的对象从 angularjs 传递到 REST 服务

unit-testing - 如何使用 ` func(w http.ResponseWriter, r *http.Request) `进行模拟测试

swift - 插入函数作为参数

java处理返回异常

java - 即使将堆大小增加到最大值后,Jmeter 也会出现超过 2000 个线程的 java.lang.OutOfMemoryError

java - 使用 Android 从图像中读取文本

javascript - Spring应用程序在登录后调用最后一个ajax调用

javascript - 如何使用 gulp test 和 karma 在浏览器中调试 Javascript 测试文件

Xcode 捕获所有未捕获的异常

java - 如何在 Android dalvik JVM 上转储堆栈跟踪的函数参数值?