使用JUnit测试异常。即使发生异常,测试也会失败

使用JUnit测试异常。即使发生异常,测试也会失败

问题描述:

我是新来的使用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(); 
     } 

结果是引发异常,但测试失败。 我错过了什么?

谢谢,托马斯

删除try-catch块。 JUnit将收到异常并进行适当处理(根据您的注释,考虑测试成功)。如果你禁止异常,那么JUnit是否被抛出是无法知道的。

@Test(expected=IOException.class) 
public void testEmptyString() throws IOException { 
    new SumarniVzorec(""); 
} 

此外,博士杰里理所当然地指出,你不能用==操作比较字符串。使用equals方法(或string.length == 0

http://junit.sourceforge.net/doc/cookbook/cookbook.htm(见 '应例外' 部分)

+1

谢谢你,但我已经尝试过,它给出了一个错误:未处理的异常类型IOError – 2010-10-09 08:45:55

+2

你仍然需要声明该方法为'抛出IOException' – developmentalinsanity 2010-10-09 08:51:24

+0

@Tomas你从哪里得到IOError?你可以发布整个错误消息(与堆栈跟踪)? – 2010-10-09 08:51:58

也许sumarniVzorec.eq​​uals( “”),而不是sumarniVzorec == “”

+0

谢谢,我修复了这个问题,但并没有解决上述问题。 – 2010-10-09 08:48:54

怎么样:

@Test 
public void testEmptyString() 
{ 
    try 
    { 
     SumarniVzorec test = new SumarniVzorec(""); 
     org.junit.Assert.fail(); 
    } 
    catch (IOException e) 
    { // Error 
     e.printStackTrace(); 
    } 

另一种方式来做到这一点:

public void testEmptyString() 
{ 
    try 
    { 
     SumarniVzorec test = new SumarniVzorec(""); 
     assertTrue(false); 

    } 
    catch (IOException e) 
    { 
     assertTrue(true); 
    }