This page is hosted for free by zzz.com.ua, if you are owner of this page, you can remove this message and gain access to many additional features by upgrading your hosting to PRO or VIP for just 41.60 UAH.
Do you want to support owner of this site? Click here and donate to his account some amount, he will be able to use it to pay for any of our services, including removing this ad.

Automation of API tests request

Automation  of API tests request 

………………………………………………………………

Code below allows you to automate API post request with body (used JAVA and OKHTTP)

import okhttp3.*;
import org.apache.commons.io.FileUtils;
import org.testng.Assert;

import java.io.File;
import java.io.IOException;

class PostWithBody
{
    static String post(String url, String request_body, String name_of_file_with_response, int expected_code) throws IOException
    {
        OkHttpClient client = OkHttp.getUnsafeOkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, request_body);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("content-type", "application/json")
                .addHeader("cache-control", "no-cache")
                .build();
        Response response = client.newCall(request).execute();
        String json = response.body().string(); // converting responce body to string text
        FileUtils.writeStringToFile(new File("test_data/"+name_of_file_with_response), json); // writin of response to file
        if (response.code() == expected_code) {
            System.out.print("Response code is " + response.code() + "\n Response body" + json + "\nTest passed");
        } else {
            Assert.fail("\n Response code is" + response.code() + "\n Response body" + json + "\nTest failed code is not 200");
        }
        return json;
    }

………………………………………………………………………………….

Then simply use created method

PostWithBody.post(Requests.baseUrlApi + "?access_token=" +access_token+ "&param1=" +param1, "json body", "publish.json", 200);