Testing HTTP requests on Android using Robolectric

With Robolectric you can not only mock HTTP responses for your code, but you can also test which HTTP requests your code sends. To do this, you can easily use either one of the static methods provided in the Robolectric class or you can use methods of the FakeHTTPLayer.

Say, you want to test, if there was a HTTP request sent at all. In this case, you can use the following code:


Or you want to check, if a call to a certain uri was made:


If you want to check for some more complex rules, you can use the method hasRequestMatchingRule of the FakeHttpLayer class and provide a request matcher that tests your criteria, e.g. if the request contains a certain header:

    new RequestMatcher() {
        public boolean matches(HttpRequest request) {
            if (request.containsHeader("X-CustomHeader")) {
                return true;

            return false;

To get the sent requests in the order of sending, you can use the method FakeHttpLayer.
and then e.g. check if the correct number of requests has been sent, the correct methods have been called, etc.:

List<HttpRequestInfo> sentRequests = 
assertTrue(sentRequests.size() == 2);

HttpRequestInfo firstRequest = sentRequests.get(0);
assertTrue(firstRequest.getHttpHost().getPort() == 8080);

Robolectric provides some very helpful methods to test if your code sents the correct HTTP requests in the correct order.

My other articles about Robolectric might also be interesting for you.