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?
Example@Test(expected=IllegalArgumentException.class)By using “expected” parameter, you can specify the exception name our test may throw. In above example, you are using “IllegalArgumentException” which will be thrown by the test if a developer uses an argument which is not permitted.
In JUnit 5, to write the test code that is expected to throw an exception, we should use Assertions. assertThrows(). In the given test, the test code is expected to throw an exception of type ApplicationException or its subtype. Note that in JUnit 4, we needed to use @Test(expected = NullPointerException.
The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case. To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method. Any exceptions thrown by the test will be reported by JUnit as a failure.
When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.
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).
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