user1767752
user1767752

Reputation: 360

@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?

Upvotes: 5

Views: 9854

Answers (2)

Michael
Michael

Reputation: 44230

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).

Upvotes: 7

Amer Qarabsa
Amer Qarabsa

Reputation: 6574

you need to add throws since this is a checked exception and you want the method to throw it instead of handling it ( for the test purposed)

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

Upvotes: 4

Related Questions