Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit4 : testing for expected exception

Tags:

java

junit

junit4

I'm trying to test with JUnit4 a method throwing an exception. Here is the code snippet :

package unit_tests;

import org.junit.Test;
import calculator.*;

@Test(expected=CalcError.class)
public void testDivision() {
    Calculator myCalc = new Calculator(10, 0);
    myCalc.setOperation(Calculator.Operation_e.DIVIDE);
    myCalc.getResult();
}

The problem is with the line @Test(expected=CalcError.class): I get the following error :

Class<CalcError> cannot be resolved to a type

Here is how CalcError is defined :

package calculator;

public class Calculator {
    public class CalcError extends Exception {
        // ...
    }

    public double getResult() throws CalcError {
        // ...
    }
}

I don't understand why CalcError is not a type, even though the unit tests are in a unit_tests package and the calculator is in a calculator package.

What am I missing ?

like image 352
Jérôme Avatar asked Jan 28 '26 07:01

Jérôme


1 Answers

CalcError is an inner class, so you need to use

@Test(expected=Calculator.CalcError.class)

See Nested Classes.

EDIT: You will need to declare the test method as throwing Calculator.CalcError as well:

@Test(expected=Calculator.CalcError.class)
public void testDivision() throws Calculator.CalcError {
    Calculator myCalc = new Calculator(10, 0);
    myCalc.setOperation(Calculator.Operation_e.DIVIDE);
    myCalc.getResult();
}

This is to please the compiler, because Calculator.CalcError is an checked Exception.

like image 125
Matthew Farwell Avatar answered Jan 30 '26 20:01

Matthew Farwell