Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JUnit testing divide by 0 arithmetic exception

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);
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
   }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading