web services testing using apache http client
Questo tutorial riguarda l'esecuzione di varie operazioni CRUD sui servizi Web e il test dei servizi Web utilizzando il client HTTP Apache:
In questo Serie completa di tutorial sul test delle API , abbiamo appreso che i servizi Web fungono da mezzo di comunicazione tra le macchine client e server che interagiscono su una rete. Abbiamo spiegato tutto Test API utilizzando POSTMAN nel nostro precedente tutorial.
In questo articolo, sottolineeremo come testare i servizi Web utilizzando il client HTTP Apache ed eseguire diverse operazioni CRUD sui servizi Web. Verranno discussi anche i diversi tipi di client REST disponibili per i test di backend.
miglior pulitore di registro per Windows 7 64 bit
Cosa imparerai:
- Cos'è un servizio Web?
- Cos'è il client REST?
- Operazioni CRUD utilizzando il client HTTP Apache
- Conclusione
Cos'è un servizio Web?
I servizi Web sono un mezzo di comunicazione tra le macchine client e server che interagisce su una rete con l'aiuto dei protocolli HTTP. I servizi Web sono generalmente API che non vengono installate o archiviate localmente ma sono disponibili nei cloud o in alcuni server remoti.
Fare riferimento all'esempio seguente per capire come funzionano i servizi web.
MakeMyTrip e Goibibo.com sono alcuni dei famosi siti web di prenotazione di voli e hotel e ci sono diversi fornitori di voli disponibili come Indigo, Air India, Etihad, ecc.
Se un cliente desidera prenotare un volo da New York a Londra, può navigare direttamente sul portale del fornitore di voli o prenotare tramite fornitori di terze parti. Se prenotano tramite fornitori di terze parti come MakeMyTrip e altri siti di prenotazione, in pochi secondi confronteranno e mostreranno i risultati fornendo i dettagli del volo come il prezzo più basso, il tempo di volo e molte altre informazioni.
La domanda che sorge qui è: come esattamente, in pochi secondi, ci stanno fornendo le informazioni? Cosa fanno esattamente?
Dall'interfaccia utente, prendono tutte le informazioni necessarie e le memorizzano in un file JSON o XML e chiamano le API del loro fornitore con un token di autenticazione mentre espongono le loro API e, in risposta, il sito del fornitore del volo invia una risposta JSON / XML a MakeMyTrip e convertono la risposta ricevuta e visualizzano i dettagli nell'interfaccia utente.
Tipi di servizi Web
Esistono due tipi di servizi web, vale a dire
- API SOAP
- API REST
Vediamo le differenze tra questi due servizi web come elencati nell'immagine sottostante.
File JSON / XML nel servizio Web
Lascia che il sistema S1 venga restituito in linguaggio J2EE e il sistema S2 venga restituito in .NET o Python e sappiamo che entrambe le tecnologie sono completamente diverse l'una dall'altra per quanto riguarda la sicurezza. Allora in che modo il sistema S2 condividerà il codice con un altro sistema?
Pertanto, il sistema S2 espone le sue API al sistema S1 senza esporre la logica aziendale e il sistema S2 condivide il nome dell'API, l'URL dell'API, il formato dell'API e la chiave di autenticazione / chiave del token per accedere al suo sistema. La comunicazione avviene tra i due sistemi utilizzando file JSON o XML.
Perché solo file JSON / XML?
I file JSON / XML vengono utilizzati perché si tratta di raccoglitori di dati. Qualsiasi informazione particolare viene memorizzata in formato JSON o XML, poiché sono leggeri e sono un linguaggio standard per comunicare tra due diverse interfacce / piattaforme o sistemi.
Pertanto, l'API viene sempre utilizzata quando due sistemi indipendenti interagiscono tra loro, localmente, all'interno del sistema o sulla rete.
Cos'è il client REST?
REST Client è uno strumento che chiama le API. Viene utilizzato nei test di backend quando non è presente un'interfaccia utente per chiamare le API. Alcuni client REST popolari sono client HTTP Apache, POSTMAN, SOAP UI, Swagger e molti altri.
Qui, in questo articolo, discuteremo solo del client HTTP Apache e tratteremo altri client HTTP diversi nei nostri articoli futuri.
Installazione del client HTTP in Eclipse
# 1) Apri Eclipse e crea un nuovo progetto Maven.
#Due) Elimina i pacchetti fittizi forniti da MAVEN, ad es. 'Src / main / java' e 'Src / test / java'
# 3) Vai al file pom.xml e rimuovi la dipendenza JUnit poiché non ne abbiamo bisogno.
# 4) Quindi, abbiamo bisogno della libreria client HTTP, libreria HTTP Core, libreria Parser JSON, libreria TestNG, libreria di binding Jackson-data
# 5) Aggiungi le dipendenze sopra (libreria) nel file pom.xml.
Libreria client HTTP:
Libreria HTTP Core:
Libreria JSON Parser:
Libreria TestNG:
# 6) Scarica le versioni più recenti e stabili. Non aggiungeremo il barattolo di selenio nel nostro progetto, poiché stiamo eseguendo test completi di backend. Il file pom.xml finale ha l'aspetto mostrato nell'immagine sottostante:
# 7) Successivamente, crea un framework per il tuo test API
per) Crea un pacchetto 'com.qa.config' -> Crea un file 'config.properties' e memorizza tutti gli URL.
b) Crea un altro pacchetto 'qa.com.base' -> Crea una classe 'testBase.java' che sarà una classe genitore per tutte le classi. Contiene funzioni comuni da utilizzare con tutti i metodi.
c) Crea un altro pacchetto 'com.qa.client' e la classe 'restClient.java'. Contiene il codice per recuperare le chiamate GET, POST, DELETE, PUT.
d) Creare un altro pacchetto 'com.qa.data' e la classe 'user.java' che definisce diverse proprietà utente.
e) Infine, creare un pacchetto 'com.qa.Test' in 'src / test / java' e dichiarare un metodo e funzioni principali per testare tutti i metodi GET, PUT, POST e Delete.
f) La struttura del framework finale sarà simile a quella mostrata di seguito:
g) Utilizza l'API fittizia fornita da questo sito REQ RES .
Metodi HTTP o operazioni CRUD
Vediamo diversi metodi HTTP o operazioni CRUD che automatizziamo.
Le operazioni elencate di seguito sono chiamate operazioni CRUD:
- C : Crea (significa chiamata POST)
- R : Recupera (significa GET chiamata)
- U : Aggiorna (significa chiamata PUT)
- D : Elimina (significa Elimina chiamata)
Parametri nei servizi Web REST
Convalida o enfatizza i seguenti parametri nei servizi Web REST:
(i) URI: L'URI è la combinazione del parametro URL + Path e del parametro della query.
Esempio: http://api.com/service/account/1
Qui, api.com è l'URL del server S2, servizio è il titolare. In questo servizio, il titolare va al account class, e da questa classe account, chiama il metodo account = 1. In ogni chiamata passiamo l'URI.
(ii) Carico utile: Dati JSON / XML che forniamo al sistema.
(iii) Codice di stato: Per ogni risposta, otteniamo i codici di stato.
Di seguito sono elencati alcuni codici:
- 200: Ok, funziona tutto bene.
- 201: Creato con successo, ogni volta che esegui una chiamata POST o crei una nuova entità.
- 400: Il payload è sbagliato, l'URL finale è sbagliato, mostra una cattiva richiesta.
- 404: Aggiorna o elimina un'entità e quell'entità non è disponibile, quindi otteniamo il risultato come richiesta non trovata.
- 500: Supponiamo che il server S2 sia inattivo, otteniamo un errore interno del server.
- 401: Errore di autenticazione
Clic Qui per ottenere tutti i codici di stato.
(iv) Intestazioni: Come token di autenticazione, ID utente / password, Tipo di contenuto, ecc.
miglior editor di testo per python mac
Operazioni CRUD utilizzando il client HTTP Apache
# 1) GET Call
Come si comporta l'operazione GET Call?
Get Call invia la richiesta e riceve la risposta. Non passiamo alcun JSON o il payload qui, passiamo un URI, in cui URL (parametro del percorso dell'endpoint, parametro di query) insieme all'intestazione, se disponibile.
domande di intervista per sviluppatore .net
Prima di scrivere il codice GET Call, tieni presente le seguenti cose:
- Hai bisogno di un metodo GET
- Quindi serve un URL
- Dopo aver premuto il pulsante di invio, riceverai la risposta. Quindi memorizzare la risposta.
- Hai bisogno di codice di stato, intestazioni.
Fare riferimento allo screenshot seguente del client POSTMAN che visualizza la risposta alla chiamata GET:
Nella classe restClient.java,
(io) Crea il metodo GET che chiamerà l'URL e riceverà la risposta sotto forma di oggetto JSON senza intestazione.
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) Crea la classe principale 'getAPITest.java' in 'src / test / java'
Produzione
# 2) Chiamata POST
POST Call crea un account o crea una nuova entità.
Esempio - Passa questi dettagli come nome, lavoro e intestazione al payload JSON. Il server S2 sarà collegato ad alcuni database, ad esempio Oracle, e avrà un nome di tabella chiamato Account table. Il metodo POST creerà una voce nel database e il server S2 passerà le informazioni al client S1. Ricorda che, l'operazione di chiamata POST viene sempre utilizzata per creare una nuova entità.
Nel metodo POST, dobbiamo passare l'URL e il payload.
Scarica questa dipendenza poiché abbiamo bisogno di convertire la classe Java in un oggetto Java che in un oggetto JSON.
Nella classe restClient.java,
(io) Crea il metodo POST, che chiamerà l'URL e pubblicherà la risposta.
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) Creare la classe principale 'postAPI_Test.java' in 'src / 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()));} }
Produzione:
# 3) PUT Call
Utilizzando l'operazione di chiamata PUT, puoi creare una nuova entità e aggiornare un'entità esistente.
Nella classe restClient.java,
(io) Crea il metodo PUT, che chiamerà l'URL e aggiornerà la risposta.
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) Crea la classe principale 'putAPI_Test.java' in 'src / 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);}
Produzione
# 4) Elimina chiamata
L'operazione di eliminazione della chiamata è semplice, ovvero elimina l'ID account 100 e passa le informazioni in un file JSON.
Nella classe restClient.java,
(io) Crea un metodo di eliminazione, che chiamerà URL ed eliminerà il record.
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) Creare la classe principale 'deleteAPI_Test.java' in 'src / 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'); }
Produzione
Prima di convalidare qualsiasi risposta, ottenere l'URL corretto dallo sviluppatore, quindi verificare se si sta ottenendo la risposta prevista dal server, preparare i casi di test per ogni scenario e disporre i casi di test in sequenza rispetto alla funzionalità.
Conclusione
In questo articolo, abbiamo spiegato come utilizzare Apache HTTP Client per automatizzare le chiamate POST, PUT, GET ed Delete in dettaglio con esempi di codice. Abbiamo anche discusso i tipi di servizi Web e l'importanza dei file JSON / XML e il motivo per cui vengono utilizzati.
Tutorial PREV | PRIMO Tutorial
Lettura consigliata
- Tutorial sui servizi Web: componenti, architettura, tipi ed esempi
- Oltre 15 tutorial SoapUI: il miglior strumento di test delle API dei servizi Web
- Domande e risposte ai colloqui di Amazon Web Services (AWS)
- Top 20 domande e risposte al colloquio sui servizi Web RESTful
- Top 25 domande e risposte ai colloqui sui servizi Web Java
- Le 45 principali domande e risposte ai colloqui sui servizi Web (RESTful, SOAP, domande di sicurezza)
- Test delle prestazioni dei servizi Web mediante LoadRunner VuGen Scripting
- Tutorial sul test delle API: una guida completa per principianti