Forum Stats

  • 3,837,125 Users
  • 2,262,228 Discussions
  • 7,900,210 Comments

Discussions

Java - test REST API

Giuseppe Lacagnina
Giuseppe Lacagnina Member Posts: 1
edited Aug 23, 2019 7:04AM in Java Programming

Dear All,

I have recently started to use Java in my work as Test Engineer (my previous experience is with C#). I need some guidance to find the best way to achieve my goal, which is to develop a JUnit-based testing solution to test a RESTful service.

Could you please point me to some resources to support me implement a simple solution? I essentially need to:

  • make HTTP requests for GET, POST, PUT, DELETE
  • retrieve the response as JSON
  • find stuff in the response for the tests

In the cases of the POST and PUT calls, I need to specify a JSON body. It is all conceptually easy but, being relatively new to Java, I am not sure how to do it (I would like to implement a nice architecture, for one thing).

I also do not know if there is some guide or some simple project already doing all these things I need.

Can anyone help? Thanks in advance!

Answers

  • Gerardo Arroyo
    Gerardo Arroyo Member Posts: 132
    edited Aug 22, 2019 5:45PM

    Hi!

    It's pretty simple to call a REST API in Java, by example (if you need a more complete example, let me know)

    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(MY_URI+ "/somepath");

    // let's asume an example with a form params
    Form form = new Form();
    form.param("param", "value"):

    // And the post
    Response response = target.request().post(Entity.form(form));

    // Now you read it...

    JsonObject responseJson = response.readEntity(JsonObject.class); 
    String acessToken = responseJson.getString("json_property1");
    String refreshToken =responseJson.getString("json_property2");

  • rpc1
    rpc1 Member Posts: 1,503
    edited Aug 23, 2019 7:04AM

    Try this framework REST Assured

    It is easy way to make integration tests for Restfull services