How to use Robolectric and still make real HTTP requests

Recently, I have been writing some unit tests for my application using Robolectric. The framework and plugin has allowed me to write some plain unit tests using Mockito which is great, however, today I came across a feature that I didn’t want to take advantage of.

I was testing a class that is responsible for making REST HTTP requests to a server and for this test I wanted to get real responses. However, when running the tests in Android Studio everything was fine, but as soon as I ran it from the command line using gradle I got the following error.


java.lang.RuntimeException: Unexpected call to execute, no pending responses are available. See Robolectric.addPendingResponse(). Request was: GET http://127.0.0.1/rest/543e7ee26c3f52cce18c365f
	at org.robolectric.tester.org.apache.http.FakeHttpLayer.emulateRequest(FakeHttpLayer.java:127)
	at org.robolectric.shadows.ShadowDefaultRequestDirector.execute(ShadowDefaultRequestDirector.java:162)
	at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java)
	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
	at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
	at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:83)
	at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:46)
	at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:63)
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:476)
	at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:439)
	at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:259)
	at com.lsc.spear.services.REST.tasks.GetAssetByIdRequest.doInBackground(GetAssetByIdRequest.java:70...

This was down to a feature in Robolectric that allows developers to test their code without making real HTTP requests. See their blog article on this here

However, in my situation I wanted to make the real requests. You can turn this feature off using the method call.

Robolectric.getFakeHttpLayer().interceptHttpRequests(false);

I put it in my @Before annotated method so it was configured for all my tests.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s