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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With