java 使用 JUnit 测试异常。即使捕获到异常,测试也会失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3896614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Testing for Exceptions using JUnit. Test fails even if the Exception is caught
提问by Tomas Novotny
I am new to testing with JUnit and I need a hint on testing Exceptions.
我是 JUnit 测试的新手,我需要有关测试异常的提示。
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
谢谢你,托马斯
回答by Nikita Rybak
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.
删除try-catch
块。JUnit 将接收异常并对其进行适当处理(根据您的注释,认为测试成功)。如果您抑制异常,则无法知道 JUnit 是否抛出异常。
@Test(expected=IOException.class)
public void testEmptyString() throws IOException {
new SumarniVzorec( "");
}
Also, dr jerryrightfully points out that you can't compare strings with ==
operator. Use equals
method (or string.length == 0
)
此外,杰瑞博士正确地指出,您不能将字符串与==
运算符进行比较。使用equals
方法(或string.length == 0
)
http://junit.sourceforge.net/doc/cookbook/cookbook.htm(see 'Expected Exceptions' part)
http://junit.sourceforge.net/doc/cookbook/cookbook.htm(参见“预期异常”部分)
回答by dr jerry
maybe sumarniVzorec.equals("") instead of sumarniVzorec == ""
也许 sumarniVzorec.equals("") 而不是 sumarniVzorec == ""
回答by EJB
how about :
怎么样 :
@Test
public void testEmptyString()
{
try
{
SumarniVzorec test = new SumarniVzorec( "");
org.junit.Assert.fail();
}
catch (IOException e)
{ // Error
e.printStackTrace();
}
回答by java_mouse
Another way to do this is :
另一种方法是:
public void testEmptyString()
{
try
{
SumarniVzorec test = new SumarniVzorec( "");
assertTrue(false);
}
catch (IOException e)
{
assertTrue(true);
}