在Mockito和JUnit单元测试中捕获或模拟意外的异常,可以通过以下几种方式来实现:
假设我们有一个方法divide
,它在除数为零时会抛出ArithmeticException
:
public class Calculator {
public int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
return a / b;
}
}
我们可以使用JUnit和Mockito来测试这个方法:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.*;
public class CalculatorTest {
@Test
public void testDivideByZero() {
Calculator calculator = new Calculator();
assertThrows(ArithmeticException.class, () -> calculator.divide(10, 0));
}
}
如果我们想捕获并验证代码是否抛出了未预期的异常,可以使用try-catch
块并结合断言:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class UnexpectedExceptionTest {
@Test
public void testUnexpectedException() {
Calculator calculator = new Calculator();
Exception exception = assertThrows(Exception.class, () -> {
// 这里故意调用一个会抛出意外异常的方法
throw new RuntimeException("Unexpected exception");
});
assertEquals("Unexpected exception", exception.getMessage());
}
}
assertThrows
: 这是JUnit提供的方法,用于验证代码是否抛出了预期的异常。try-catch
块捕获异常,并通过断言验证异常的类型和消息。通过上述方法,可以在Mockito和JUnit单元测试中有效地捕获和模拟意外的异常,从而提高代码的健壮性和测试覆盖率。
领取专属 10元无门槛券
手把手带您无忧上云