user1855193
user1855193

Reputation: 141

Java: Mocking http/https calls in unit test

I am trying to set up unit-tests in my code wherein I would like to mock the rest calls going to an external web service. I know a couple of ways to do so:

  1. Stub the methods that make the call to external webservice using PowerMock to return mock response objects.

  2. For unit tests, change the host address of the web service to point to localhost and then use the WireMock to attach to localhost and send out responses.

What I want to do is not change the host address in (2) and let WireMock (or any other third party library) intercept the call to a given host and based on the call send out the response.

In other words, I would like to configure WireMock in such a way that if my code is calling for instance http://www.google.com then WireMock will intercept that call and respond with something I configure. (Basically stub www.google.com).

Upvotes: 1

Views: 2346

Answers (1)

Tom
Tom

Reputation: 4149

Unfortunately WireMock can't do this.

You have a three options (that I can think of):

  1. Use BetaMax, which configures itself as a proxy for Java HTTP clients, or
  2. Modify your hosts file to point e.g. www.google.com to 127.0.0.1
  3. If you're using Apache HTTP client 4.2+, you can implement a custom DnsResolver to bind the hostname you're using to 127.0.0.1.

Upvotes: 1

Related Questions