Я пытаюсь автоматизировать GraphQA API через httpclient (рамки автоматизации). но получаю ошибку 400 - PullRequest
1 голос
/ 25 февраля 2020

Я пытаюсь автоматизировать GraphQL API через среду автоматизации httplient. Вот мой код:

public class Restclient {

        public CloseableHttpResponse post(String url, String entitystring, HashMap<String, String> headermap)
                throws ClientProtocolException, IOException {
            // entity string is to pass the payload(kind of body)

            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(url); // post request(http)
            httppost.setEntity(new StringEntity(entitystring)); // for payload

            // for headers

            for (Map.Entry<String, String> entry : headermap.entrySet()) {

                httppost.addHeader(entry.getKey(), entry.getValue());
            }

            CloseableHttpResponse closablehttpresponse = httpclient.execute(httppost);
            return closablehttpresponse;

        }

    }

Ниже я использую класс User. java для создания параметризованных методов Constructor и Getter и Setter для получения и установки json во время выполнения.


    package com.qa.data; 
    public class users {
    String type;
        String title;
        String description;
        int difficultylevel;
        String privilege;
        String image;
        String visibility;

        public users(String type, String title, String description, int difficultylevel, String privilege, String image,
                String visibility) {
            this.type = type;
            this.title = title;
            this.description = description;
            this.difficultylevel = difficultylevel;
            this.privilege = privilege;
            this.image = image;
            this.visibility = visibility;
        }

        public users() {
            // TODO Auto-generated constructor stub
        }


        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public int getDifficultylevel() {
            return difficultylevel;
        }

        public void setDifficultylevel(int difficultylevel) {
            this.difficultylevel = difficultylevel;
        }

        public String getPrivilege() {
            return privilege;
        }

        public void setPrivilege(String privilege) {
            this.privilege = privilege;
        }

        public String getImage() {
            return image;
        }

        public void setImage(String image) {
            this.image = image;
        }

        public String getVisibility() {
            return visibility;
        }

        public void setVisibility(String visibility) {
            this.visibility = visibility;
        }

    }

Ниже я использую аннотацию testng для запуска теста. Итак, я использовал всю информацию заголовков json в формате значения ключа


        package com.qa.test;
        import java.io.File;
        import java.io.IOException;
        import java.util.HashMap;

        import org.apache.http.client.methods.CloseableHttpResponse;
        import org.testng.Assert;
        import org.testng.annotations.AfterMethod;
        import org.testng.annotations.BeforeMethod;
        import org.testng.annotations.Test;

        import com.fasterxml.jackson.core.JsonGenerationException;
        import com.fasterxml.jackson.databind.JsonMappingException;
        import com.fasterxml.jackson.databind.ObjectMapper;
        import com.qa.base.Testbase;
        import com.qa.client.Restclient;
        import com.qa.data.users;

        public class PostAPITest extends Testbase {

            Testbase testbase;
            String ServiceURL;
            String ApiURL;
            String URL;
            String Token;

            Restclient restclient; 
            CloseableHttpResponse closablehttpresponse; 

            @BeforeMethod
            public void setup() {

                testbase = new Testbase();
                ServiceURL = prop.getProperty("URL");
                ApiURL = prop.getProperty("ServiceURL");
                URL = ServiceURL + ApiURL;
                Token = prop.getProperty("token");
            }

            @Test
            public void postapitestcreate() throws JsonGenerationException, JsonMappingException, IOException {
                restclient = new Restclient();

                HashMap<String, String> headermap = new HashMap();

                headermap.put("Content-Type", "application/json");
                headermap.put("User-Agent", "PostmanRuntime/7.22.0");
                headermap.put("Accept", "*/*");
                headermap.put("Cache-Control", "no-cache");
                headermap.put("Host", "ec2-13-229-70-209.ap-southeast-1.compute.amazonaws.com:7783");
                headermap.put("Accept-Encoding", "gzip");
                headermap.put("accept-language", "id");
                headermap.put("Postman-Token", "5e3afc56-0a02-4c63-80b1-21cbc52a2403");
                headermap.put("Connection", "Keep-alive");
                headermap.put("Content-Length", "333");

                headermap.put("x-token",
                        "Token");
                    ObjectMapper mapper = new ObjectMapper();
            users user = new users("video", "Kelas 10 Mathematics - Pytho", "Read class", 1, "visitor", "title.jpg",
                    "published");


            mapper.writeValue(
                    new File("/Users/amikumar/eclipse-workspace/ZeniusBackend/src/main/java/com/qa/data/users.json"), user);


            String jsonasstring = mapper.writeValueAsString(user);
            System.out.println(jsonasstring);


            closablehttpresponse = restclient.post(URL, jsonasstring, headermap);



            int statuscode = closablehttpresponse.getStatusLine().getStatusCode();
            Assert.assertEquals(statuscode,testbase.response_status_code_201);
        }

    }

Я пытаюсь получить код состояния, но вместо 201 получаю 400 Error. Может кто-нибудь, пожалуйста, помогите?

Я использовал три класса.

  • Один для остального клиента, который я использовал closablehttpresponse, чтобы получить ответ на почтовый запрос.
  • Тогда у меня есть Пользователь использовал. java для отправки отправить json запрос
  • Затем я использовал тест postapi. java для запуска теста.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...