Search code examples
javaexceptionjunit4assert

@Test(expected = Exception.class) does not work for me, what am I missing?


I am using sts but also using mvn clean install on the command line. I created this simple to test as an example.

import org.junit.Test;

import junit.framework.TestCase;

public class QuickTest extends TestCase {

    @Test(expected = Exception.class)
    public void test() {
        throwsException();
    }

    private void throwsException() throws Exception {
        throw new Exception("Test");
    }
}

My STS (Eclipse) IDE complains that the line calling the method testThrowsException(); unhandled exception type Exception.

If I try to run the test I get the same error

java.lang.Error: Unresolved compilation problem: 
    Unhandled exception type Exception

What am I doing wrong?


Solution

  • The problem is that you're declaring Exception as expected in an annotation. This is runtime behaviour, as determined by JUnit. Your code must still conform to all of Java's normal rules at compile-time. Under Java's normal rules, when a method throws a checked exception, you must either 1) mark it as thrown in the method signature or 2) catch it and deal with it. Your code does neither. For your test, you want to do the former in order for JUnit to fail:

    public class QuickTest extends TestCase
    {
        @Test(expected = Exception.class)
        public void test() throws Exception {
            throwsException();
        }
    }
    

    Or you can change Exception to RuntimeException in both cases so that it's an unchecked exception (i.e. not subject to the same rules).