错误编译带有预期异常的junit测试 [英] error compiling junit test with expect exception

查看:63
本文介绍了错误编译带有预期异常的junit测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难使用junit 4的预期注释来查看异常.我无法编译代码,因为有未处理的异常.

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");
    }
}

我收到一个编译错误,提示未处理的异常类型UnsupportedEncodingException"

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

这很有道理,我可以通过声明simpleTest引发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?

推荐答案

据我所知,UnsupportedEncodingException是一个已检查的异常.因此,编译器期望对检查的异常使用throws子句.如果您说您尝试过使用未经检查的异常(例如ArithmeticException),那么我想您的代码将可以正常工作.

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测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆