如您所知,异常情况下会引发异常。那么如何模拟这些异常呢?我觉得这是挑战。对于这样的代码片段:
public String getServerName() {
try {
InetAddress addr = InetAddress.getLocalHost();
String hostname = addr.getHostName();
return hostname;
}
catch (Exception e) {
e.printStackTrace();
return "";
}
}
有人有好的想法吗?
最佳答案
您可以告诉 junit 正确的行为是获取异常。
在 JUnit 4 中,它类似于:
@Test(expected = MyExceptionClass.class)
public void functionUnderTest() {
…
}
关于java - 如何对异常进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3305453/