Testing for Exceptions using JUnit. Test fails eve

2019-06-25 14:24发布

问题:

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

回答1:

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)



回答2:

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



回答3:

how about :

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


回答4:

Another way to do this is :

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

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