(This is a follow up question to this one.)
I'm having a problem with JUnit4 tests in eclipse. I'm trying to use the @Test(expected=...) annotation to unit test exception throwing. The problem is that when I run the tests, they come back as errors instead of passing, even though I'm expecting the exceptions to be thrown.
I'm using eclipse 3.4.0 and JUnit 4.3.1.
Here's the code:
Class to test:
public class IPAddress
{
private byte[] octets;
private IPAddress()
{
octets = new byte[4];
}
public IPAddress(String addr) throws InvalidIPAddressException
{
this();
if(addr == null || !isValid(addr))
throw new InvalidIPAddressException(addr);
String strOctets[] = addr.split("\\.");
for (int i = 0; i < strOctets.length; i++)
octets[i] = Byte.parseByte(strOctets[i]);
}
public static boolean isValid(String addr)
{
String strOctets[] = addr.split("\\.");
if (strOctets.length != 4)
return false;
for (int i = 0; i < strOctets.length; i++)
{
try
{
int num = Integer.parseInt(strOctets[i]);
if (num < 0 || num > 255)
return false;
} catch (NumberFormatException e)
{
return false;
}
}
return true;
}
public byte[] getOctets()
{
return octets;
}
}
Exception:
public class InvalidIPAddressException extends Exception
{
public InvalidIPAddressException(String addr)
{
super("\"" + addr + "\" is not a valid IP address");
}
}
Test case:
public class IPAddressTest extends TestCase
{
@Test(expected=InvalidIPAddressException.class)
public void testNullParameter() throws InvalidIPAddressException
{
@SuppressWarnings("unused")
IPAddress addr = new IPAddress(null);
fail("InvalidIPAddressException not thrown.");
}
@Test(expected=InvalidIPAddressException.class)
public void testHostnameParameter() throws InvalidIPAddressException
{
@SuppressWarnings("unused")
IPAddress addr = new IPAddress("http://www.google.com");
fail("InvalidIPAddressException not thrown.");
}
@Test
public void testValidIPAddress() throws InvalidIPAddressException
{
IPAddress addr = new IPAddress("127.0.0.1");
byte[] octets = addr.getOctets();
assertTrue(octets[0] == 127);
assertTrue(octets[1] == 0);
assertTrue(octets[2] == 0);
assertTrue(octets[3] == 1);
}
public static void main(String[] args)
{
TestRunner.run(IPAddressTest.class);
}
}