vendredi 29 avril 2016

How to use JUnit and Mockito to mock inner logic

I'm king of new to Junit and Mockito and trying to understand how to mock parts of logic of a class.

I have a method which does a http post and get call, but it might be a DB lookup. How do I mock the response from the HTTP call in this method

  BufferedReader in = new BufferedReader(new InputStreamReader(httpsConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}

I mean there must a way to test my logic without doing to real http call or db lookup or whatever.

// HTTP GET request
public String sendGet(URL url) throws Exception {

    s_logger.debug("URL: " + url);
    HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();

    // Add request header
    httpsConnection.setRequestMethod("GET");
    httpsConnection.setRequestProperty("Content-Type", "application/xml");

    if (sessionId != null) {
        httpsConnection.setRequestProperty("sessionId", sessionId);
    } else {
        httpsConnection.setRequestProperty("username", ACCOUNT_USERNAME);
        httpsConnection.setRequestProperty("password", ACCOUNT_PASSWORD);
    }

    httpsConnection.setInstanceFollowRedirects(false);
    httpsConnection.setUseCaches(false);

    // Print Request Header
    s_logger.debug("Request Header: " + httpsConnection.getRequestProperties());

    int responseCode = httpsConnection.getResponseCode();
    s_logger.debug("Response Code : " + responseCode);

    Map<String, List<String>> headerFields = httpsConnection.getHeaderFields();
    s_logger.debug("Response Header: " + headerFields);

    BufferedReader in = new BufferedReader(new InputStreamReader(httpsConnection.getInputStream()));
    String inputLine;
    StringBuilder response = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    // Set Session ID
    final String SESSION_KEY = "sessionId";
    if (this.sessionId == null && httpsConnection.getHeaderFields().containsKey(SESSION_KEY)) {
        this.sessionId = httpsConnection.getHeaderFields().get(SESSION_KEY).get(0);
        s_logger.debug("SESSION ID : " + this.sessionId);
    }

    // print result
    s_logger.debug("RESPONSE: " + response.toString());
    return response.toString();
}

Thanks for any help or suggestion.

Aucun commentaire:

Enregistrer un commentaire