web services testing using apache http client
이 자습서는 웹 서비스에서 다양한 CRUD 작업을 수행하고 Apache HTTP 클라이언트를 사용하여 웹 서비스를 테스트하는 방법에 대해 설명합니다.
이것에 완전한 API 테스트 튜토리얼 시리즈 , 우리는 웹 서비스가 네트워크를 통해 상호 작용하는 클라이언트와 서버 시스템 간의 통신 매체 역할을한다는 것을 배웠습니다. 우리는 POSTMAN을 사용한 API 테스트 이전 튜토리얼에서.
이 기사에서는 Apache HTTP 클라이언트를 사용하여 웹 서비스를 테스트하고 웹 서비스에서 다양한 CRUD 작업을 수행하는 방법을 강조합니다. 백엔드 테스트에 사용할 수있는 다양한 REST 클라이언트 유형에 대해서도 설명합니다.
컴퓨터 문제 해결을위한 최고의 소프트웨어
학습 내용 :
웹 서비스 란?
웹 서비스는 HTTP 프로토콜을 사용하여 네트워크를 통해 상호 작용하는 클라이언트와 서버 시스템 간의 통신 매체입니다. 웹 서비스는 일반적으로 로컬에 설치되거나 저장되지 않지만 클라우드 또는 일부 원격 서버에서 사용할 수있는 API입니다.
웹 서비스 작동 방식을 이해하려면 아래 예제를 참조하십시오.
MakeMyTrip 및 Goibibo.com은 유명한 항공편 및 호텔 예약 웹 사이트 중 일부이며 Indigo, Air India, Etihad 등과 같은 다양한 항공편 공급 업체가 있습니다.
고객이 뉴욕에서 런던으로가는 항공편을 예약하려는 경우 항공편 공급 업체 포털에서 직접 검색하거나 타사 공급 업체를 통해 예약 할 수 있습니다. MakeMyTrip 및 기타 예약 사이트와 같은 타사 공급 업체를 통해 예약하는 경우 몇 초 내에 최저 가격, 비행 시간 및 훨씬 더 많은 기타 정보와 같은 항공편 세부 정보를 제공하는 결과를 비교하고 표시합니다.
여기서 문제는 얼마나 정확하게 몇 초 내에 정보를 우리에게 제공 하는가입니다. 정확히 무엇을하나요?
UI에서 필요한 모든 정보를 가져와 JSON 또는 XML 파일에 저장하고 API를 노출 할 때 인증 토큰을 사용하여 공급 업체 API를 호출하고 이에 대한 응답으로 비행 공급 업체의 사이트는 JSON / XML 응답을 MakeMyTrip에 다시 보냅니다. 수신 된 응답을 변환하고 UI에 세부 사항을 표시합니다.
웹 서비스 유형
웹 서비스에는 두 가지 유형이 있습니다.
- SOAP API
- REST API
아래 이미지에 나열된 두 웹 서비스의 차이점을 살펴 보겠습니다.
웹 서비스의 JSON / XML 파일
S1 시스템은 J2EE 언어로 반환되고 S2 시스템은 .NET 또는 Python으로 반환되며 두 기술이 보안 문제로 인해 서로 완전히 다르다는 것을 알고 있습니다. 그렇다면 S2 시스템은 다른 시스템과 코드를 어떻게 공유할까요?
따라서 S2 시스템은 비즈니스 로직을 노출하지 않고 API를 S1 시스템에 노출하고 S2 시스템은 API 이름, API URL, API 형식 및 인증 키 / 토큰 키를 공유하여 시스템에 액세스합니다. JSON 또는 XML 파일을 사용하여 두 시스템간에 통신이 이루어집니다.
왜 JSON / XML 파일 만 사용합니까?
JSON / XML 파일은 데이터 수집기이기 때문에 사용됩니다. 가볍고 두 개의 서로 다른 인터페이스 / 플랫폼 또는 시스템간에 통신하기위한 표준 언어이므로 특정 정보는 JSON 또는 XML 형식으로 저장됩니다.
따라서 API는 두 개의 독립적 인 시스템이 로컬로, 시스템 내에서 또는 네트워크를 통해 서로 상호 작용할 때 항상 사용됩니다.
REST 클라이언트 란?
REST 클라이언트는 API를 호출하는 도구입니다. API를 호출 할 UI가 없을 때 백엔드 테스트에 사용됩니다. 인기있는 REST 클라이언트로는 Apache HTTP 클라이언트, POSTMAN, SOAP UI, Swagger 등이 있습니다.
이 기사에서는 Apache HTTP 클라이언트에 대해서만 설명하고 향후 기사에서 다른 HTTP 클라이언트에 대해 다룰 것입니다.
Eclipse에서 Http 클라이언트 설정
#1) Eclipse를 열고 새 Maven 프로젝트를 만듭니다.
#두) MAVEN에서 제공하는 더미 패키지를 삭제합니다. 'src / main / java' 과 'src / test / java'
#삼) pom.xml 파일로 이동하여 필요하지 않은 JUnit 종속성을 제거합니다.
# 4) 그런 다음 HTTP Client 라이브러리, HTTP Core 라이브러리, JSON Parser 라이브러리, TestNG 라이브러리, Jackson-data bind Library가 필요합니다.
# 5) pom.xml 파일에 위의 종속성 (라이브러리)을 추가합니다.
HTTP 클라이언트 라이브러리 :
HTTP Core 라이브러리 :
JSON 파서 라이브러리 :
TestNG 라이브러리 :
# 6) 안정적인 최신 버전을 다운로드하십시오. 우리는 완전한 백엔드 테스트를 수행하고 있기 때문에 프로젝트에 Selenium jar를 추가하지 않을 것입니다. 최종 pom.xml 파일은 아래 이미지와 같습니다.
# 7) 다음으로 API 테스트를위한 프레임 워크를 만듭니다.
에) “com.qa.config”패키지 생성 -> 'config.properties'파일을 만들고 모든 URL을 저장합니다.
비) 다른 패키지“qa.com.base”생성 -> 모든 클래스의 상위 클래스가 될 'testBase.java'클래스를 작성하십시오. 모든 메소드에서 사용되는 공통 기능이 포함되어 있습니다.
씨) 다른 패키지“com.qa.client”와 클래스“restClient.java”를 만듭니다. 여기에는 GET, POST, DELETE, PUT 호출을 가져 오는 코드가 포함됩니다.
디) 다른 사용자 속성을 정의하는 다른 패키지“com.qa.data”와 클래스“user.java”를 만듭니다.
이다) 마지막으로“src / test / java”아래에“com.qa.Test”패키지를 생성하고 모든 GET, PUT, POST 및 Delete 메소드를 테스트하는 주요 메소드와 함수를 선언합니다.
f) 최종 프레임 워크 구조는 다음과 같습니다.
지) 이 사이트에서 제공하는 더미 API 사용 REQ RES .
HTTP 메서드 또는 CRUD 작업
우리가 자동화하는 다양한 HTTP 메서드 또는 CRUD 작업을 살펴 보겠습니다.
아래 나열된 작업을 CRUD 작업이라고합니다.
- 씨 : 만들기 (POST 호출을 의미)
- 아르 자형 : 검색 (GET 호출을 의미 함)
- 유 : 업데이트 (PUT 호출을 의미)
- 디 : 삭제 (통화 삭제를 의미)
REST 웹 서비스의 매개 변수
REST 웹 서비스에서 아래 매개 변수를 확인하거나 강조합니다.
(i) URI : URI는 URL + Path 매개 변수와 쿼리 매개 변수의 조합입니다.
예: http://api.com/service/account/1
여기, api.com S2 서버의 URL입니다. 서비스 홀더입니다. 이 서비스에서 소유자는 계정 이 계정 클래스에서 account = 1 메소드를 호출합니다. 각각의 모든 호출에서 우리는 URI를 전달합니다.
(ii) 탑재량 : 시스템에 제공하는 JSON / XML 데이터.
(iii) 상태 코드 : 각각의 모든 응답에 대해 상태 코드를받습니다.
다음은 몇 가지 코드입니다.
- 200 : 좋아, 모든 것이 잘 작동합니다.
- 201 : POST 호출을 수행하거나 새 엔티티를 생성 할 때마다 성공적으로 생성되었습니다.
- 400 : 페이로드가 잘못되었고 최종 URL이 잘못되었으며 잘못된 요청을 표시합니다.
- 404 : 엔티티를 업데이트하거나 삭제하고 해당 엔티티를 사용할 수없는 경우 요청을 찾을 수 없음으로 결과를 얻습니다.
- 500 : S2 서버가 다운되었다고 가정하면 내부 서버 오류가 발생합니다.
- 401 : 인증 오류
딸깍 하는 소리 여기 모든 상태 코드를 얻으려면.
(iv) 헤더 : 인증 토큰, 사용자 ID / 비밀번호, 콘텐츠 유형 등
Wi-Fi 용 보안 키를 얻는 방법
Apache HTTP 클라이언트를 사용한 CRUD 작업
# 1) 전화 받기
GET 호출 작업은 어떻게 작동합니까?
Get Call은 요청을 보내고 응답을받습니다. 여기서는 JSON이나 페이로드를 전달하지 않고 URL (엔드 포인트 경로 매개 변수, 쿼리 매개 변수)이있는 경우 헤더와 함께 하나의 URI를 전달합니다.
안드로이드 인터뷰 질문 및 답변 pdf
GET Call 코드를 작성하기 전에 다음 사항에 유의하십시오.
- GET 메서드 필요
- 그런 다음 URL이 필요합니다.
- 보내기 버튼을 누르면 응답을 받게됩니다. 그런 다음 응답을 저장하십시오.
- 상태 코드, 헤더가 필요합니다.
GET 호출 응답을 표시하는 POSTMAN 클라이언트의 아래 스크린 샷을 참조하십시오.
restClient.java 클래스에서
(나는) URL을 호출하고 Header없이 JSON 객체의 형태로 응답을받을 GET Method를 생성합니다.
package com.qa.Client; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import org.apache.http.Header; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; public class restClient { // create GET Method, which will call the URL and get the response in the form of JSON object without Header public CloseableHttpResponse getMethod(String Url) throws ClientProtocolException, IOException, JSONException{ /*Call HTTPClients class from HTTPClient library added in POM.xml. Call createDefault() method present in HTTPClients class, which will create a client connection. And this createDefault() method returns 'CloseableHttpClient' object which is an abstract class. And we are creating a reference to that abstract class */ CloseableHttpClient httpClient=HttpClients.createDefault(); /*create an object for HttpGet class, which is used for HTTP GET Request. And pass the URL which is to be loaded*/ HttpGet htttpGet = new HttpGet(Url); /*execute the HTTP GET Request, means it will hit the GET API call as we click SEND button from POSTMAN client. httpClient.execute() method returns the response 'CloseableHttpResponse' interface and store it in reference variable So the complete response is stored in CloseableHttpResponse And fetch all the details, in our test case/test method */ CloseableHttpResponse closeableHttpResponse = httpClient.execute(htttpGet); return closeableHttpResponse; } }
(ii) 'src / test / java'아래에 기본 클래스 'getAPITest.java'를 만듭니다.
산출
# 2) POST 호출
POST 호출은 계정을 생성하거나 새 엔티티를 생성합니다.
예 – 이름, 작업 및 헤더와 같은 세부 정보를 JSON 페이로드에 전달합니다. S2 서버는 Oracle이라고 말하는 일부 데이터베이스에 연결되며 Account table이라는 테이블 이름이 있습니다. POST 메소드는 데이터베이스에 항목을 생성하고 S2 서버는 정보를 S1 클라이언트에 전달합니다. POST 호출 작업은 항상 새 엔터티를 만드는 데 사용됩니다.
POST 메서드에서 URL과 페이로드를 전달해야합니다.
Java 클래스를 JSON 개체가 아닌 Java 개체로 변환해야하므로이 종속성을 다운로드하십시오.
restClient.java 클래스에서
(나는) URL을 호출하고 응답을 게시하는 POST 메서드를 만듭니다.
public class restClient { public CloseableHttpResponse POST(String url,String entityString,HashMap headermap) throwsClientProtocolException, IOException{ /*Call HTTPClients class from HTTPClient library added in POM.xml and createDefault() method present in HTTPClients class, which will create a client connection and this createDefault() method returns 'CloseableHttpClient' object which is an abstract class and we are creating reference to that abstract class */ CloseableHttpClient httpClient=HttpClients.createDefault(); /*create an object for HttpPost class, which is used for HTTP POST Request and pass the URL which is to be loaded */ HttpPost htttpPost = new HttpPost(url); /*define pay load, use setEnity method present in HTTPPOST class and pass the payload entity */ htttpPost.setEntity(new StringEntity(entityString)); //Create a for loop and iterate the hashmap, and store the header for(Map.Entry entry : headermap.entrySet()){ htttpPost.addHeader(entry.getKey(),entry.getValue()); } //Execute the POST request CloseableHttpResponse closeableHttpResponse = httpClient.execute(htttpPost); return closeableHttpResponse; } }
(ii) 'src / test / java'아래에 기본 클래스 'postAPI_Test.java'를 만듭니다.
//Inherit testBase class public class postAPI_Test extends testBase { //Create global methods testBase testbase; String serviceURL; String apiURL; String URL; restClient restClient; HttpResponse closeableHttpResponse; // In before method call the properties file @BeforeMethod public void setUp() throws ClientProtocolException, IOException, JSONException{ //call the constructor of base class and execute the properties file testbase = new testBase(); serviceURL = prop.getProperty('URL'); apiURL = prop.getProperty('serviceURL'); URL = serviceURL+apiURL; } //Main method which calls the GET method @Test public void POSTAPITest() throws ClientProtocolException, IOException, JSONException{ restClient = new restClient(); //Pass the Request Header HashMap headrMap = new HashMap(); headrMap.put('Content-Type', 'application/json'); /*Use Jackson API for doing marshaling, means converting java to java object to JSON Object and vice versa Use ObjectMapper class */ ObjectMapper mapper = new ObjectMapper(); //Create object of Users class, expected users users user = new users('John','Manager'); //Convert java object 'user' to JSON Object using writeValue(), pass the path where to store the JSON file and the object to be converted */ mapper.writeValue(new File('.\data\users.json'), user ); //convert java object to json in string String userJsonString = mapper.writeValueAsString(user); System.out.println(userJsonString); //Call the POST Method closeableHttpResponse = restClient.POST(URL, userJsonString, headrMap); //Fetches status, header, and JSON response from CloseableHttpResponse //1.Fetch Status Code int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();//Get the Status code System.out.println('Status Code --->' +statusCode); //Validate the status code using Assert class Assert.assertEquals(statusCode, response_Status_Code_201,'Status is not 200'); /*2.Fetch the JSON String use EntityUtils class and call to String method, where we have to pass entity and format entity is available in closeableHttpResponse and pass UTF-8 format because we want pure string so complete JSON will be stored in a String, so we need to convert an entire string into a JSON object */ String responseString = EntityUtils.toString(closeableHttpResponse.getEntity(), 'UTF-8'); /*as we added one JSON library, from that library call JSON class and pass the response string. So this JSON object converts the string into JSON */ JSONObject responseJson = new JSONObject(responseString); System.out.println('Response JSONfrom API --->'+responseJson); /*Convert JSON to java actual User Object we are getting */ users userResObj = mapper.readValue(responseString, users.class); Assert.assertTrue(user.getName().equals(userResObj.getName())); Assert.assertTrue(user.getJob().equals(userResObj.getJob()));} }
산출:
# 3) PUT 호출
PUT 호출 작업을 사용하여 새 항목을 만들고 기존 항목을 업데이트 할 수 있습니다.
restClient.java 클래스에서
(나는) URL을 호출하고 응답을 업데이트하는 PUT 메서드를 만듭니다.
public class restClient { public CloseableHttpResponse PUT(String url,String entityString,HashMap headermap) throwsClientProtocolException, IOException{ /*Call HTTPClients class from HTTPClient library added in POM.xml. Call createDefault() method present in HTTPClients class, which will create a client connection and this createDefault() method returns 'CloseableHttpClient' object which is an abstract class and we are creating reference to that abstract class*/ CloseableHttpClient httpClient=HttpClients.createDefault(); /*create an object for HttpPut class, which is used for HTTP PUT Request and pass the URL which is to be loaded */ HttpPut htttpPut = new HttpPut(url); /*define pay load, use setEnity method present in HTTPPUT class and pass the payload entity */ htttpPut.setEntity(new StringEntity(entityString)); /*create a for loop, iterate and store the header */ for(Map.Entry entry : headermap.entrySet()){ htttpPut.addHeader(entry.getKey(),entry.getValue()); } //Execute the PUT request CloseableHttpResponse closeableHttpResponse = httpClient.execute(htttpPut); return closeableHttpResponse; } }
(ii) 'src / test / java'아래에 기본 클래스 'putAPI_Test.java'를 만듭니다.
//Inherit testBase class public class putAPI_Test extends testBase { //Create global methods testBase testbase; String serviceURL; String apiURL; String URL; restClient restClient; HttpResponse closeableHttpResponse; // in before method call the properties file @BeforeMethod public void setUp() throws ClientProtocolException, IOException, JSONException{ //Call the constructor of the base class and execute the properties file testbase = new testBase(); serviceURL = prop.getProperty('URL'); apiURL = prop.getProperty('serviceURL'); URL = serviceURL+apiURL; } //Main method which calls PUT method @Test public void PUTAPITest() throws ClientProtocolException, IOException, JSONException{ restClient = new restClient(); //Pass the Request Header HashMap headrMap = new HashMap(); headrMap.put('Content-Type', 'application/json'); /*use Jackson API, for doing marshaling means converting java to java object to JSON Object and vice versa, use ObjectMapper class */ ObjectMapper mapper = new ObjectMapper(); //Create object of Users class, new users users user = new users('JohnMarry Dicosta','HRManager'); /*Convert java object 'user' to JASON Object using writeValue() and pass the path where to store the JSON file and the object to be converted */ mapper.writeValue(new File('.\data\users.json'), user ); //convert java object - > JSON - >String String userJsonString = mapper.writeValueAsString(user); System.out.println(userJsonString); //Call the PUT Method closeableHttpResponse = restClient.PUT(URL, userJsonString, headrMap); /*fetch status, header, JSON response from CloseableHttpResponse Fetch Status Code */ int statusCode = closeableHttpResponse.getStatusLine().getStatusCode(); System.out.println('Status Code --->' +statusCode); //Validate the status code using Assert class Assert.assertEquals(statusCode, response_Status_Code_200,'Status is 200'); /*2.Fetch the JSON String, use EntityUtils class and call to String method where we have to pass entity and format entity is available in closeableHttpResponse and pass UTF-8 format because we want a pure string. So complete JSON will be stored in a String, so we need to convert an entire string into a JSON object */ String responseString = EntityUtils.toString(closeableHttpResponse.getEntity(), 'UTF-8'); /* From JSON library, call JSON class and pass the response string. This JSON object converts the string to JSON */ JSONObject responseJson = new JSONObject(responseString); System.out.println('Response JSONfrom API --->'+responseJson);}
산출
# 4) 통화 삭제
통화 삭제 작업은 간단합니다. 즉, 계정 ID-100을 삭제하고 정보를 JSON 파일로 전달합니다.
restClient.java 클래스에서
(나는) URL을 호출하고 레코드를 삭제하는 Delete 메서드를 만듭니다.
public CloseableHttpResponse Delete(String url) throws ClientProtocolException, IOException{ /*Call HTTPClients class from HTTPClient library added in POM.xml and createDefault() method present in HTTPClients class, which will create a client connection and this createDefault() method returns 'CloseableHttpClient' object which is an abstract class and we are creating reference to that abstract class */ CloseableHttpClient httpClient=HttpClients.createDefault(); /*create an object for HttpDelete class, which is used for HTTP Delete Request, and pass the URL to be loaded*/ HttpDelete htttpDelete = new HttpDelete(url); //execute Delete request CloseableHttpResponse closeableHttpResponse =httpClient.execute(htttpDelete); return closeableHttpResponse; }
(ii)“src / test / java”아래에 메인 클래스“deleteAPI_Test.java”를 생성합니다.
public class deleteAPI_Test extends testBase { //Create global methods testBase testbase; String serviceURL; String deleteuserUrl; String URL; restClient restClient; HttpResponse closeableHttpResponse; // In before method call the properties file @BeforeMethod public void setUp() throws ClientProtocolException, IOException, JSONException{ //call the constructor of the base class and execute the properties file testbase = new testBase(); serviceURL = prop.getProperty('URL'); deleteuserUrl = prop.getProperty('deleteuser'); URL = serviceURL+deleteuserUrl; } //The Main method which calls the Delete method @Test public void deleteAPI() throws ClientProtocolException, IOException, JSONException{ restClient = new restClient(); //Method returns closeableHttpResponse type closeableHttpResponse = restClient.Delete(URL); /*fetch status code, header, JSON response from CloseableHttpResponse -Fetch Status Code */ int statusCode = closeableHttpResponse.getStatusLine().getStatusCode(); System.out.println('Status Code --->' +statusCode); //Validate the status code using Assert class Assert.assertEquals(statusCode, response_Status_Code_204,'Status is 204 No Content'); }
산출
응답의 유효성을 검사하기 전에 개발자로부터 올바른 URL을 얻은 다음 서버에서 예상되는 응답을 받고 있는지 확인하고 각 시나리오에 대한 테스트 케이스를 준비하고 기능에 따라 테스트 케이스를 순서대로 정렬하십시오.
결론
이 기사에서는 코드 예제를 통해 POST, PUT, GET 및 Delete 호출을 자동화하기 위해 Apache HTTP 클라이언트를 사용하는 방법을 자세히 다루었습니다. 또한 웹 서비스 유형과 JSON / XML 파일의 중요성 및 사용 이유에 대해서도 논의했습니다.