Tom*_*tny 4 java junit unit-testing exception-handling
我是JUnit测试的新手,我需要一个关于测试Exceptions的提示.
我有一个简单的方法,如果它获得一个空输入字符串,则抛出异常:
public SumarniVzorec( String sumarniVzorec) throws IOException
{
if (sumarniVzorec == "")
{
IOException emptyString = new IOException("The input string is empty");
throw emptyString;
}
Run Code Online (Sandbox Code Playgroud)
我想测试如果参数是一个空字符串实际抛出异常.为此,我使用以下代码:
@Test(expected=IOException.class)
public void testEmptyString()
{
try
{
SumarniVzorec test = new SumarniVzorec( "");
}
catch (IOException e)
{ // Error
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
结果是抛出异常,但测试失败.我错过了什么?
托马斯,谢谢你
Nik*_*bak 14
删除try-catch块.JUnit将接收异常并适当地处理它(根据您的注释考虑测试成功).如果你压制异常,就没有办法知道JUnit是否被抛出.
@Test(expected=IOException.class)
public void testEmptyString() throws IOException {
new SumarniVzorec( "");
}
Run Code Online (Sandbox Code Playgroud)
此外,杰里博士理所当然地指出你不能将字符串与==运算符进行比较.使用equals方法(或string.length == 0)
http://junit.sourceforge.net/doc/cookbook/cookbook.htm(参见'预期的例外'部分)
| 归档时间: |
|
| 查看次数: |
11514 次 |
| 最近记录: |