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

北城以北 提交于 2019-12-23 12:27:25

问题


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);
    }


来源:https://stackoverflow.com/questions/3896614/testing-for-exceptions-using-junit-test-fails-even-if-the-exception-is-caught

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!