Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7789447
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T21:18:06+00:00 2026-06-01T21:18:06+00:00

I’ve got a class: public class WebReader implements IWebReader { HttpClient client; public WebReader()

  • 0

I’ve got a class:

public class WebReader implements IWebReader {

    HttpClient client;

    public WebReader() {
        client = new DefaultHttpClient();
    }

    public WebReader(HttpClient httpClient) {
        client = httpClient;
    }

    /**
     * Reads the web resource at the specified path with the params given.
     * @param path Path of the resource to be read.
     * @param params Parameters needed to be transferred to the server using POST method.
     * @param compression If it's needed to use compression. Default is <b>true</b>.
     * @return <p>Returns the string got from the server. If there was an error downloading file, 
     * an empty string is returned, the information about the error is written to the log file.</p>
     */
    public String readWebResource(String path, ArrayList<BasicNameValuePair> params, Boolean compression) {
            HttpPost httpPost = new HttpPost(path);
            String result = "";

            if (compression)
                httpPost.addHeader("Accept-Encoding", "gzip");
            if (params.size() > 0){
                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
                } catch (UnsupportedEncodingException e1) {
                    e1.printStackTrace();
                }
            }

            try {
                HttpResponse response = client.execute(httpPost);
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    InputStream content = entity.getContent();
                    if (entity.getContentEncoding() != null
                            && "gzip".equalsIgnoreCase(entity.getContentEncoding()
                                    .getValue()))
                        result = uncompressInputStream(content);
                    else
                        result = convertStreamToString(content);
                } else {
                    Log.e(MyApp.class.toString(), "Failed to download file");
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return result;
        }

    private String uncompressInputStream(InputStream inputStream)
            throws IOException {...}

    private String convertStreamToString(InputStream is) {...}

}

I cannot find a way to test it using a standard framework. Especially, I need to simulate total internet lost from inside the test.

There are suggestions to manually turn the Internet in the emulator off while performing the test. But it seems to me as not quite a good solution, because the automatic tests should be… automatic.

I added a “client” field to the class trying to mock it from inside the test class. But implementation of the HttpClient interface seems quite complex.

The Robolectric framework allows the developers to test Http connection as far as I know. But I guess there is some way to write such a test without using so big additional framework.

So are there any short and straightforward ways of unit testing classes that use HttpClient? How did you solve this in your projects?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T21:18:07+00:00Added an answer on June 1, 2026 at 9:18 pm

    I added a “client” field to the class trying to mock it from inside the test class. But implementation of the HttpClient interface seems quite complex.

    I am a little bit confuse about this statement. From the question title, you are asking about unit-testing httpClint, by mocking a FakeHttpClient may help you unit-testing other part of app except httpClient, but doesn’t help anything for unit-testing httpClient. What you need is a FakeHttpLayer for unit-testing httpClient (no remote server, network requires, hence unit-testing).

    HttpClient Dummy Test:

    If you only need examine app behavior in the situation that internet is lost, then a classic Android Instrument Test is sufficient, you can programmatically turn the Internet in the emulator off while performing the test:

    public void testWhenInternetOK() {
      ... ...
      webReader.readWebResource();
      // expect HTTP 200 response.
      ... ...
    }
    
    public void testWhenInternetLost() {
      ... ...
      wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 
      wifiManager.setWifiEnabled(false);
      webReader.readWebResource();
      // expect no HTTP response.
    ... ...
    }
    

    This requires the remote http server is completely setup and in a working state, and whenever you run your test class, a real http communication is made over network and hit on http server.

    HttpClient Advanced Test:

    If you want to test app behavior more precisely, for instance, you want to test a http call in you app to see if it is handle different http response properly. the Robolectric is the best choice. You can use FakeHttpLayer and mock the http request and response to whatever you like.

    public void setup() {
      String url = "http://...";
      // First http request fired in test, mock a HTTP 200 response (ContentType: application/json)
      HttpResponse response1 = new DefaultHttpResponseFactory().newHttpResponse(HttpVersion.HTTP_1_1, 200, null);
      BasicHttpEntity entity1 = new BasicHttpEntity();
      entity1.setContentType("application/json");
      response1.setEntity(entity1);
      // Second http request fired in test, mock a HTTP 404 response (ContentType: text/html)
      HttpResponse response2 = new DefaultHttpResponseFactory().newHttpResponse(HttpVersion.HTTP_1_1, 404, null);
      BasicHttpEntity entity2 = new BasicHttpEntity();
      entity2.setContentType("text/html");
       response2.setEntity(entity2);
      List<HttpResponse> responses = new ArrayList<HttpResponse>();
      responses.add(response1);
      responses.add(response2);
      Robolectric.addHttpResponseRule(new FakeHttpLayer.UriRequestMatcher("POST", url), responses);
    }
    
    public void testFoo() {
      ... ...
      webReader.readWebResource(); // <- a call that perform a http post request to url.
      // expect HTTP 200 response.
      ... ...
    }
    
    public void testBar() {
      ... ...
      webReader.readWebResource(); // <- a call that perform a http post request to url.
      // expect HTTP 404 response.
    ... ...
    }
    

    Some pros of using Robolectric are:

    • Purely JUnit test, no instrument test so don’t need start emulator (or real device) to run the test, increase development speed.
    • Latest Robolectric support single line of code to enable/disable FakeHttpLayer, where you can set http request to be interpreted by FakeHttpLayer (no real http call over network), or set the http request bypass the FakeHttpLayer(perform real http call over network). Check out this SO question for more details.

    If you check out the source of Robolectric, you can see it is quite complex to implement a FakeHtppLayer properly by yourself. I would recommend to use the existing test framework instead of implementing your own API.

    Hope this helps.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I've got a string that has curly quotes in it. I'd like to replace
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I want use html5's new tag to play a wav file (currently only supported
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
public static bool CheckLogin(string Username, string Password, bool AutoLogin) { bool LoginSuccessful; // Trim
i got an object with contents of html markup in it, for example: string
Seemingly simple, but I cannot find anything relevant on the web. What is the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.