Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for Exceptions using JUnit. Test fails even if the Exception is caught

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

like image 492
Tomas Novotny Avatar asked Dec 07 '22 01:12

Tomas Novotny


2 Answers

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)

like image 103
Nikita Rybak Avatar answered Dec 09 '22 14:12

Nikita Rybak


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

like image 39
dr jerry Avatar answered Dec 09 '22 15:12

dr jerry