使用JUnit测试异常。即使捕获到异常,测试也会失败

时间:2010-10-09 08:38:31

标签: java unit-testing exception-handling 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();
        }

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

谢谢Tomas

4 个答案:

答案 0 :(得分:14)

删除try-catch块。 JUnit将接收异常并适当地处理它(根据您的注释考虑测试成功)。如果你压制异常,就无法知道JUnit是否被抛出。

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

此外, Dr jerry 正确地指出您无法将字符串与==运算符进行比较。使用equals方法(或string.length == 0

http://junit.sourceforge.net/doc/cookbook/cookbook.htm(参见“预期的例外”部分)

答案 1 :(得分:1)

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

答案 2 :(得分:0)

怎么样:

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

答案 3 :(得分:0)

另一种方法是:

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

    }
    catch (IOException e)
    {
       assertTrue(true);
    }
相关问题