Java – JUnit test on URLConnection, use EasyMock

javajunitunit-testing

Hey, have been trying to work this out for last day or so but hitting brick wall. Trying to unit test this bit of code. But not sure if need to use EasyMock or not?? Seem few examples online but seem to be using older techniques.

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;
}

It just take's in a url checks its valid and returns T or F.

Best Solution

I have always observed that Mocking Can be avoided as much as possible because it can lead to difficult to maintain JUnit tests and defeat the whole purpose.

My suggestion would be to create a temporary server on your local machine from a JUnit itself. At the beginning of JUnit you can create a server(not more than 10-15 lines of coding required) using Java sockets and then in your code pass the URL for the local server. This way you are reducing mocking and ensuring maximum code coverage.

Something like this -

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;
    }
}
}