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:

assertTrue(Robolectric.httpRequestWasMade());

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

assertTrue(Robolectric.
        httpRequestWasMade("http://www.myserver.com/"));

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:

assertTrue(Robolectric.getFakeHttpLayer()
    .hasRequestMatchingRule(
    new RequestMatcher() {
        @Override
        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.
getSentHttpRequestInfos
and then e.g. check if the correct number of requests has been sent, the correct methods have been called, etc.:

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

HttpRequestInfo firstRequest = sentRequests.get(0);
assertTrue(firstRequest.getHttpRequest()
        .containsHeader("X-CustomHeader"));
assertTrue(firstRequest.getHttpHost().getPort() == 8080);

Conclusion
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.