Search code examples
javaexceptionjunit

Junit is not getting custom exception


I am trying to test a custom exception in junit test but it is not getting it.
Here is the method that I created

public String Validate(Student obj) throws NullStudentObjectException, NullNameException, NullMarksArrayException {
    if(obj == null) {
        throw new NullStudentObjectException();
    }
    else{
        if(obj.getName() == null)
            throw new NullNameException();
        else if(obj.getMarks() == null
            throw new NullMarksArrayException();
        return(findGrades(obj);
    }
}

Here I am calling the method.

public void testCase() {
    StudentReport objSR = new StudnetReport();
    try {
        objSR.Validate(data[6]);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

StudentReport is the class for validate method and in data[6] I am passing null.
And here is the test case

@Test (expected = NullStudentObjectException.class)
public void testTestCase() {
    objTest.testCase();
}

While running this code it's not getting the custom exception but in the printStackTrace, it's printing that it here is a null object exception.
And one more thing when I'm creating a built-in exception like divide by zero JUnit is getting that exception.


Solution

  • The problem is that this code:

    try {
        objSR.Validate(data[6]);
    } catch (Exception e) {
        e.printStackTrace();
    }
    

    swallows the exception and it doesn't reach the higher level where the test expects it. You either need to remove this try... catch... around the objSR.Validate(data[6]) call, or you need to re-throw the exception after catching and logging it, like that:

    public void testCase() {
        StudentReport objSR = new StudentReport();
        try {
            objSR.Validate(data[6]);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
    

    And one more thing when I'm creating a built-in exception like divide by zero JUnit is getting that exception.

    Because your code is catching Exception, but ArithmeticException is inherited from RuntimeException, that's why it's not caught.