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)
。答案无误!