views:

34

answers:

3

Hi, 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

+4  A: 

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.

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

Also, dr jerry rightfully points out that you can't compare strings with == operator. Use equals method (or string.length == 0)

http://junit.sourceforge.net/doc/cookbook/cookbook.htm (see 'Expected Exceptions' part)

Nikita Rybak
Thank you, but I tried that already and it gives an error: unhandled Exception type IOError
Tomas Novotny
You still need to declare the method as `throws IOException`
developmentalinsanity
@Tomas where do you get IOError from? Can you post whole error message (with stacktrace)?
Nikita Rybak
@developmentalinsanity Thanks, my bad. But it wouldn't compile otherwise, so it can't really solve IOError.
Nikita Rybak
@developmentalinsanity Thank you, works perfectly.
Tomas Novotny
+1  A: 

maybe sumarniVzorec.equals("") instead of sumarniVzorec == ""

dr jerry
Thank you, I repaired that, but it didn't solve the problem mentioned above.
Tomas Novotny
A: 

how about :

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