Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用mockito检查是否未引发异常?_Java_Unit Testing_Exception_Exception Handling_Mockito - Fatal编程技术网

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

Java 如何使用mockito检查是否未引发异常?,java,unit-testing,exception,exception-handling,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"); //

我有一个简单的
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");
   }
}

只要您没有显式地声明期望出现异常,JUnit就会自动使任何抛出未捕获异常的测试失败

例如,以下测试将失败:

@Test
public void exampleTest(){
    throw new RuntimeException();
}
如果您想进一步检查测试是否会在异常时失败,您可以简单地添加一个
throw new RuntimeException()编码到要测试的方法中,运行测试并检查它们是否失败


当您没有手动捕获异常并且测试失败时,JUnit将在失败消息中包含完整的堆栈跟踪,这允许您快速找到异常源。

使用断言。assertThatThrownBy().isInstanceOf()两次(如下所示)即可达到此目的

import org.assertj.core.api.Assertions;
import org.junit.Test;

public class AssertionExample {

    @Test
    public void testNoException(){
        assertNoException();
    }



    private void assertException(){
        Assertions.assertThatThrownBy(this::doNotThrowException).isInstanceOf(Exception.class);
    }

    private void assertNoException(){
        Assertions.assertThatThrownBy(() -> assertException()).isInstanceOf(AssertionError.class);
    }

    private void doNotThrowException(){
        //This method will never throw exception
    }
}

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

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

您不需要对Mockito执行此操作:如果调用该方法时抛出异常,JUnit将使测试失败。所以你不需要做任何额外的事情。好吧,但它看起来不像是在测试什么?i、 没有验证或断言等?目前,您只是测试此方法不会引发异常。您可以自由添加更多检查,例如,
getBalanceForPerson
返回预期值-但这是JUnit检查,
assertEquals(expectedBalance,result)
。答案无误!