Tamar
Tamar

Reputation: 13

How to mock GET HTTP request using JAVA

How can I mock GET http request using JAVA? I have this method:

public HTTPResult get(String url) throws Exception{
        try {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            return new HTTPResult(response.getBody(), response.getStatusCode().value());
        }
        catch (ResourceAccessException e) {
            String responseBody = e.getCause().getMessage();
            JSONObject obj = new JSONObject(responseBody);
            return new HTTPResult(obj.getString("responseBody"), Integer.parseInt(obj.getString("statusCode")));
        }
    }

How can i verify i am getting: responseBody - some json and statusCode for example 200?

Upvotes: 0

Views: 418

Answers (1)

GhostCat
GhostCat

Reputation: 140407

If you want a "true" unit test, you have to look into using a mocking framework, such as EasyMock, or Mockito (I recommend the later one). That might make it necessary to rework your production code, as calls to new() often make problems with these frameworks (there are other frameworks that are better there: JMockit, or PowerMockito, but again: if possible go with Mockito).

If you are rather asking for a more "end to end" kind of test: there are test frameworks for Jersey ( see here for example ). Meaning: you can actually "unit test" your REST endpoints almost completely, without the need of running a real server.

Upvotes: 1

Related Questions