(这是这个问题的后续问题。)
我在 Eclipse 中遇到 JUnit4 测试问题。我正在尝试使用 @Test(expected=...) 注释来单元测试异常抛出。问题是当我运行测试时,它们会作为错误返回而不是通过,即使我期望抛出异常。
我正在使用 eclipse 3.4.0 和 JUnit 4.3.1。
这是代码:
测试类:
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;
}
}
例外:
public class InvalidIPAddressException extends Exception
{
public InvalidIPAddressException(String addr)
{
super("\"" + addr + "\" is not a valid IP address");
}
}
测试用例:
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);
}
}