Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anyone had success mocking HttpRequests with Robolectric?

I'm just starting with Robolectric. It seems to be working fine to mock most Android classes but when my class under test tries to create a DefaultHttpClient() it gets the dreaded "Stub!" error.

The class under test fails at this line:

HttpClient httpclient = new DefaultHttpClient();

even though the article at http://robolectric.blogspot.com/2011/01/how-to-test-http-requests.html?showComment=1297722651278#c3540420071421225744 seems to suggest this should just work.

My test looks like this:

@Before
public void setUp() throws Exception
{
  Robolectric.addPendingHttpResponse(200, "OK");
  service = new CheckinService();
}

@Test
public void testIt() throws IOException
{
  // Fails at HttpClient httpclient = new DefaultHttpClient()
  service.doStuff(Robolectric.application,
                  REG_ID,
                  TEST_DOMAIN);
}

Any idea what I'm doing wrong?

like image 542
Fasaxc Avatar asked Jan 20 '23 12:01

Fasaxc


2 Answers

Fixed it within eclipse. Took me a while to figure out how to fix that but here it is: Go to your test project preferences > build path > order&export > select robolectric jar and press move to top.

like image 166
meredrica Avatar answered Jan 29 '23 07:01

meredrica


In your pom.xml move the robolectric dependency on top of the android one.

like image 29
Macarse Avatar answered Jan 29 '23 07:01

Macarse