简体   繁体   中英

JUnit4 : testing for expected exception

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.

CalcError is an inner class of Calculator . It is not imported by import calculator.*; You'd have to add import calculator.Calculator.CalcError or qualify CalcError ( expected=Calculator.CalcError.class ).

Having public classes as inner classes is not a good idea. You should move that to its own file. Only private classes should be nested. You could probably access the Error class by using Calculator.CalcError.class but I'd strong advise against it.

Apart from that I think JUnit lacks a bit of exception detection capabilities as you cannot set a message. I unit test for exceptions by catching them and then calling Assert.fail after the method call that should throw an exception:

try {
    someMethod();
    Assert.fail("SomeException should have been thrown");
catch(SomeException se) {
}

Since CalcError is an inner class to Calculator you need to reference it like this

@Test(expected=Calculator.CalcError.class)
public void testDivision() {

由于这是一个经过检查的异常,您需要向方法签名添加throws Exception ,否则编译器会抱怨异常。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM