嘿,过去一天左右一直在努力解决这个问题,但碰壁了。尝试对这段代码进行单元测试。但是不确定是否需要使用 EasyMock?在线示例似乎很少,但似乎使用的是较旧的技术。
public boolean verifyConnection(final String url) {
boolean result;
final int timeout = getConnectionTimeout();
if (timeout < 0) {
log.info("No need to verify connection to client. Supplied timeout = {}", timeout);
result = true;
} else {
try {
log.debug("URL: {} Timeout: {} ", url, timeout);
final URL targetUrl = new URL(url);
final HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
result = true;
} catch (ConnectException e) {
log.warn("Could not connect to client supplied url: " + url, e);
result = false;
} catch (MalformedURLException e) {
log.error("Malformed client supplied url: " + url, e);
result = false;
} catch (IOException e) {
log.warn("Could not connect to client supplied url: " + url, e);
result = false;
}
}
return result;
}
它只需要在 url 中检查其有效性并返回 T 或 F。
最佳答案
我一直观察到 Mocking 可以尽可能避免,因为它会导致难以维护 JUnit 测试并破坏整个目的。
我的建议是通过 JUnit 本身在您的本地机器上创建一个临时服务器。 在 JUnit 的开头,您可以使用 Java 套接字创建一个服务器(需要不超过 10-15 行代码),然后在您的代码中传递本地服务器的 URL。这样您就可以减少模拟并确保最大的代码覆盖率。
像这样的——
public class SimpleServer extends Thread {
public void run() {
try {
serverSocket = new ServerSocket(port);
while (true) {
Socket s = serverSocket.accept();
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
serverSocket = null;
}
}
}
关于java - URLConnection 上的 JUnit 测试,使用 EasyMock?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5564804/