Всем привет. Сегодня мы рассмотрим довольно специфическое тестирование, которое требует определенных знаний в области HTTP. Рассмотрим на примере Java.
Для начала нам понадобится скачать HTTP-клиент и все необходимые библиотеки (jars), а затем добавить их к проекту.
HTTP-клиент: http://hc.apache.org/downloads.cgi
Дополнительные библиотеки для импортов: http://www.java2s.com/Code/Jar/CatalogJar.htm
Перед тем как тестировать веб-сервисы, ознакомьтесь с их основами, например, на W3School.
Непосредственное тестирование мы будем проводить используя два формата для хранения данных:
1) JSON-файл
2) XML -файл.
Проверка HTTP Response
В первую очередь мы проверим HTTP response (ответы) используя коды и наиболее известные:
- 200- Ok
- 404- Page not found
- 401- Unauthorized
Ниже представлен метод, который проверяет HTTP-ответы:
1 2 3 4 5 6 7 8 9 10 11 12 |
public static void testStatusCode(String restURL) throws ClientProtocolException, IOException { // Create Object and pass the url HttpUriRequest request = new HttpGet(restURL); // send the response or execute the request HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); // Verify the response code is equal to 200 Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(),HttpStatus.SC_OK); } |
Проверка Content type в ответе
1 2 3 4 5 6 7 8 9 10 11 |
public static void testMimeType(String restURL, String expectedMimeType) throws ClientProtocolException, IOException { // Create object of HTTP request HttpUriRequest request = new HttpGet(restURL); // Send the request HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); // Verify the response type Assert.assertEquals(expectedMimeType,ContentType.getOrDefault(httpResponse.getEntity()).getMimeType()); } |
Парсинг данных с XML-файла
1 2 3 4 5 6 7 8 9 10 11 |
public static void testContent(String restURL, String element, String expectedValue) throws ClientProtocolException, IOException, SAXException, ParserConfigurationException { // Parse the URL Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(restURL); // Get the element from response using element tag name NodeList nodelist = doc.getElementsByTagName(element); // Verify the response content using Assert Assert.assertEquals(expectedValue,nodelist.item(0).getTextContent()); } |
Парсинг данных с JSON-файла
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public static void testContentJSON(String restURL, String element, String expectedValue) throws ClientProtocolException, IOException, SAXException, ParserConfigurationException, JSONException { // Create request object HttpUriRequest request = new HttpGet(restURL); // send response or execute query HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); // Convert the response to a String format String result = EntityUtils.toString(httpResponse.getEntity()); // Convert the result as a String to a JSON object JSONObject jo = new JSONObject(result); // Verify content Assert.assertEquals(expectedValue, jo.getString(element)); } |
Полный код:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
import java.io.IOException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import org.junit.Assert; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class APITestClass { // This is request which we are sending to server String restURL_XML = "http://parabank.parasoft.com/parabank/services/bank/customers/12212/"; // sending request and we are passing parameter in url itself String restURL_JSON = "http://api.openweathermap.org/data/2.5/weather?q=Amsterdam"; @Test public void TestAllOperations(){ try { testStatusCode(restURL_XML); testStatusCode(restURL_JSON); testMimeType(restURL_XML,"application/xml"); testMimeType(restURL_JSON,"application/json"); testContent(restURL_XML,"lastName","Smith"); testContentJSON(restURL_JSON,"name","Amsterdam"); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void testStatusCode(String restURL) throws ClientProtocolException, IOException { HttpUriRequest request = new HttpGet(restURL); HttpResponse httpResponse = HttpClientBuilder.create().build() .execute(request); Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_OK); } public static void testMimeType(String restURL, String expectedMimeType) throws ClientProtocolException, IOException { HttpUriRequest request = new HttpGet(restURL); HttpResponse httpResponse = HttpClientBuilder.create().build() .execute(request); Assert.assertEquals(expectedMimeType, ContentType.getOrDefault(httpResponse.getEntity()) .getMimeType()); } public static void testContent(String restURL, String element, String expectedValue) throws ClientProtocolException, IOException, SAXException, ParserConfigurationException { Document doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder().parse(restURL); NodeList nodelist = doc.getElementsByTagName(element); Assert.assertEquals(expectedValue, nodelist.item(0).getTextContent()); } public static void testContentJSON(String restURL, String element, String expectedValue) throws ClientProtocolException, IOException, SAXException, ParserConfigurationException, JSONException { HttpUriRequest request = new HttpGet(restURL); HttpResponse httpResponse = HttpClientBuilder.create().build() .execute(request); // Convert the response to a String format String result = EntityUtils.toString(httpResponse.getEntity()); // Convert the result as a String to a JSON object JSONObject jo = new JSONObject(result); Assert.assertEquals(expectedValue, jo.getString(element)); } } |
Запустив тесты с помощью JUnit можно проверить успешное выполнение программы: