error compiling junit test with expect exception

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?


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.

链接地址: http://www.djcxy.com/p/81714.html

上一篇: 从JUnit测试中抛出异常

下一篇: 编译期望异常的错误编译junit测试