error compiling junit test with expect exception

ぐ巨炮叔叔 提交于 2019-12-20 05:13:23

问题


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.



来源:https://stackoverflow.com/questions/13185647/error-compiling-junit-test-with-expect-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!