当前位置:优学网  >  在线题库

JUnit测试除以0算术异常

发表时间:2022-07-30 00:32:57 阅读:285

首先,我对Java相当陌生&我的需求是创建一个方法来划分两个整数,并为此创建一个JUnit测试方法,该方法应该预期零除算术异常.然而,我的测试失败了,出现了一个断言错误,即使测试方法中没有涉及0.我怎样才能解决这个问题?

public class Calculate {

    public static int division(int num1, int num2) throws ArithmeticException {
        try {
            return num1/ num2;
        } catch (ArithmeticException e) {
            throw new ArithmeticException("Cannot divide by 0");
        }
    }

试验方法

@Test (expected = java.lang.ArithmeticException.class)
public void division() {
    int firstNum = 10;
    int secondNum = 2;
    int expected = 5;
    Calculate test = new Calculate();
    int actual = test.division(firstNum, secondNum);
    assertEquals(expected, actual);
}
🎖️ 优质答案
  • It looks like you are trying to test everything with a single test. Instead, you should write a sepearate test for each scenario:

       // "happy path" that division works correctly
       @Test 
       public void division() {
           int firstNum = 10;
           int secondNum = 2;
           int expected = 5;
           Calculate test = new Calculate();
           int actual = test.division(firstNum, secondNum);
           assertEquals(expected, actual);
       }
    
       // error path that exception is thrown
       @Test (expected = java.lang.ArithmeticException.class)
       public void divisionByZero() {
           int firstNum = 10;
           int secondNum = 0;
           Calculate test = new Calculate();
           int actual = test.division(firstNum, secondNum);
       }
  • @Test(expected = ...) only works with JUnit 4. It's better to use assertThrows. This was added in JUnit 5 and backported to JUnit 4.13:

    @Test
    public void divisionByZero() {
        int firstNum = 10;
        int secondNum = 0;
        Calculate test = new Calculate();
        ArithmeticException thrown = assertThrows(ArithmeticException.class,
                () -> test.division(firstNum, secondNum));
        assertEquals("Cannot divide by 0", thrown.getMessage());
    }
  • 相关问题