使用 JUnit 测试异常。即使捕获异常,测试也会失败
我是 JUnit 测试的新手,我需要有关测试异常的提示。
我有一个简单的方法,如果它获取空输入字符串,它会引发异常:
public SumarniVzorec( String sumarniVzorec) throws IOException
{
if (sumarniVzorec == "")
{
IOException emptyString = new IOException("The input string is empty");
throw emptyString;
}
我想测试如果参数是空字符串,是否实际引发异常。为此,我使用以下代码:
@Test(expected=IOException.class)
public void testEmptyString()
{
try
{
SumarniVzorec test = new SumarniVzorec( "");
}
catch (IOException e)
{ // Error
e.printStackTrace();
}
结果是抛出异常,但测试失败。 我缺少什么?
谢谢你,托马斯
I am new to testing with JUnit and I need a hint on testing Exceptions.
I have a simple method that throws an exception if it gets an empty input string:
public SumarniVzorec( String sumarniVzorec) throws IOException
{
if (sumarniVzorec == "")
{
IOException emptyString = new IOException("The input string is empty");
throw emptyString;
}
I want to test that the exception is actually thrown if the argument is an empty string. For that, I use following code:
@Test(expected=IOException.class)
public void testEmptyString()
{
try
{
SumarniVzorec test = new SumarniVzorec( "");
}
catch (IOException e)
{ // Error
e.printStackTrace();
}
The result is that the exception is thrown, but the test fails.
What am I missing?
Thank you, Tomas
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
删除
try-catch
块。 JUnit 将接收异常并适当处理它(根据您的注释,认为测试成功)。如果您抑制异常,JUnit 就无法知道它是否被抛出。另外,jerry 博士正确地指出,您不能使用
==
运算符来比较字符串。使用equals
方法(或string.length == 0
)http://junit.sourceforge.net/doc/cookbook/cookbook.htm(请参阅“预期异常”部分)
Remove
try-catch
block. JUnit will receive exception and handle it appropriately (consider test successful, according to your annotation). And if you supress exception, there's no way of knowing for JUnit if it was thrown.Also, dr jerry rightfully points out that you can't compare strings with
==
operator. Useequals
method (orstring.length == 0
)http://junit.sourceforge.net/doc/cookbook/cookbook.htm (see 'Expected Exceptions' part)
也许 sumarniVzorec.equals("") 而不是 sumarniVzorec == ""
maybe sumarniVzorec.equals("") instead of sumarniVzorec == ""
怎么样:
how about :
另一种方法是:
Another way to do this is :