Android http testing with Robolectric

user2576401 picture user2576401 · Sep 15, 2013 · Viewed 7.4k times · Source

I have an Android app where the main part of the app is the APIcalls.java class where I make http requests to get data from server an display the data in the app.

I wanted to create unit test for this Java class since it's the most part of the app. Here is the method for getting the data from server:

StringBuilder sb = new StringBuilder();

try {

  httpclient = new DefaultHttpClient(); 
  Httpget httpget = new HttpGet(url);

  HttpEntity entity = null;
  try {
    HttpResponse response = httpclient.execute(httpget);
    entity = response.getEntity();
  } catch (Exception e) {
    Log.d("Exception", e);
  }


  if (entity != null) {
    InputStream is = null;
    is = entity.getContent();

    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(is));

      while ((line = reader.readLine()) != null) {
       sb.append(line + "\n");
     }
      reader.close();
    } catch (IOException e) {

           throw e;

       } catch (RuntimeException e) {

           httpget.abort();
           throw e;

       } finally {

         is.close();

       }
       httpclient.getConnectionManager().shutdown();
  }
} catch (Exception e) {
  Log.d("Exception", e);
}

String result = sb.toString().trim();

return result;

I thought I can make simple API calls from the tests like this:

api.get("www.example.com")

But every time I make some http calls from the tests, I get an error:

Unexpected HTTP call GET

I know I am doing something wrong here, but can anyone tell me how can I properly test this class in Android?

Answer

user2576401 picture user2576401 · Oct 1, 2013

Thank you for all your answers but I found what I was looking for. I wanted to test real HTTP calls.

By adding Robolectric.getFakeHttpLayer().interceptHttpRequests(false); you tell Robolectric not to intercept these requests and it allows you to make real HTTP calls