Issue
First of all, I'm fairly new to Java & my requirement is to create a method to divide two integers and a JUnit test method for that, which is supposed to expect the divide by zero arithmetic exception. However, my test fails with an assertion error even though there's no 0 involved in the test method. How can I fix this?
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 Method
@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);
}
Solution
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);
}
Answered By - Code-Apprentice
Answer Checked By - Candace Johnson (JavaFixing Volunteer)