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
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)
maybe sumarniVzorec.equals("") instead of sumarniVzorec == ""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With