Pedro Borges
Pedro Borges

Reputation: 83

Testing methods that make http requests

I have some methods in my app that make http requests. Is there a good way to simulate network failures and bad responses for the unit tests?

Upvotes: 8

Views: 6101

Answers (7)

duffymo
duffymo

Reputation: 308998

Maybe Spring test mocks would be of some assistance.

Upvotes: 1

skaffman
skaffman

Reputation: 403581

Wrap the library that makes the HTTP calls (e.g. java.net.URLConnection or Commons HttpClient) behind an interface, and then write implementations or mocks of that interface that simulates the failure conditions.

Your interface can just represent the operations that your application needs to perform, rather than the whole range of HTTP client functionality.

Upvotes: 1

Chris Simmons
Chris Simmons

Reputation: 1853

What we do in this situation is abstract the layer that's making the call. Instead of having your logic directly make the http request, have your code call a function. Within that function can be something like:

if (in_test) {
   response = get_test_response();
} else {
   response = make_http_request();
}

Then you can have your unit tests set some value accessible by the get_test_response() function. This way you can programatically change what the result of that call will be.

Upvotes: -2

George Stocker
George Stocker

Reputation: 57907

Have You tried HTTPUnit and JWebUnit?

Upvotes: 1

Alex Martelli
Alex Martelli

Reputation: 882571

Suitable Mock Objects should let you perform such simulations easily; if you're unfamiliar with the concept, there's a good tutorial here.

Upvotes: 12

karim79
karim79

Reputation: 342735

Pull out your lan wire, or turn off your wireless router while the requests are being made :)

Upvotes: 0

Spencer Ruport
Spencer Ruport

Reputation: 35117

For network failures nothing beats first unplugging your computers ethernet cable (or d/c it's wireless) and then unplugging whatever cable gives you access to the cloud.

If by bad responses you mean HTTP errors you can write ASP scripts that will always throw specific errors. If you want to test malformed HTTP packets you'll have to write a simple socket app to do that.

Upvotes: 1

Related Questions