error compiling junit test with expect exception

2020-04-21 09:00发布

问题:

I am having difficulty using junit 4's expected annotation to look at exceptions. I can't compile the code because there's an unhandled exception.

Here's a simple example that creates the situation:


import static org.junit.Assert.*;
import java.io.UnsupportedEncodingException;
import org.junit.Test;

public class Simple {
    @Test(expected=UnsupportedEncodingException.class)
    public void simpleTest(){
        String a = "";
        a.getBytes("UTF-123");
    }
}

I get a compilation error saying "Unhandled exception type UnsupportedEncodingException"

This makes sense, and I can fix this by declaring that simpleTest throws UnsupportedEncodingException but I've seen lots of examples online where people don't do that (which would be nice, when writing lots of test cases).

Is there a way to configure the test case so that I don't have to explicitly declare what exceptions will be thrown?

回答1:

As far as I know, UnsupportedEncodingException is a checked exception. So, compiler would expect a throws clause for a checked exception. I guess your code will work, if say you tried with an unchecked exception like ArithmeticException.



标签: junit junit4