How to test HttpUrlConnection ?

4,790 views
Skip to first unread message

Gal Ben-Haim

unread,
Sep 2, 2012, 6:14:40 AM9/2/12
to robol...@googlegroups.com
Robolectric's examples for testing Http connections - http://robolectric.blogspot.co.il/2011/01/how-to-test-http-requests.html
are all about DeafultHttpClient, but Google recommends using HttpUrlConnection instead as the Apache client is deprecated.

how should I test Http connections that use HttpUrlConnection ?

Jan Berkel

unread,
Sep 3, 2012, 6:48:19 AM9/3/12
to robol...@googlegroups.com

this is not possible yet. is anybody working on this feature?
i guess it's more complicated because you would need to hook into the system class loader which cannot be done dynamically.


  jan

  



 

Aaron VonderHaar

unread,
Sep 3, 2012, 5:40:30 PM9/3/12
to robol...@googlegroups.com
I haven't actually done this in a project, but a quick look around
shows a couple interesting ideas:

- Using Jetty to mock responses:
http://stackoverflow.com/questions/10534878/how-to-unit-test-an-helper-function-that-use-httpconnection

- Creating mock URLs under test, and stubbing URL.openConnection.

Please keep us updated here if you find a good solution or think it
best to try adding this to robolectric.

--Aaron V.
--
--Aaron V.
[ http://github.com/avh4 ]

Gal Ben-Haim

unread,
Sep 4, 2012, 6:40:38 AM9/4/12
to robol...@googlegroups.com
have you seen an example for the second idea ?

Levi

unread,
Sep 4, 2012, 12:25:19 PM9/4/12
to robol...@googlegroups.com
I'm not sure if this is what you were looking for, but here is how you could use Mockito to test an HttpURLConnection object with Robolectric.

Gal Ben-Haim

unread,
Sep 5, 2012, 9:15:31 AM9/5/12
to robol...@googlegroups.com
thanks for the example !

for those interested, I ended up injecting a mock HttpUrlConnection to the class under test,
I also used mock InputStream and OutputStream to test for correct posting of data and result handling.
Reply all
Reply to author
Forward
0 new messages