In this article, I will discuss API testing with Java and demonstrate with examples.
First, let’s understand what API (Application-programming interface) is?
API is a set of programming instructions and standards for accessing a Web-based software application or Web tool. API is a software-to-software interface, not a user interface. With APIs, applications talk to each other without any user knowledge or intervention. When you buy movie tickets online and enter your credit card information, the movie ticket Web site uses an API to send your credit card information to a remote application that verifies whether your information is correct. Once payment is confirmed, the remote application sends a response back to the movie ticket Web site saying it’s OK to issue the tickets.
What Json (JavaScript Object Notation) is?
JSON is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays. An object is an unordered collection of zero or more name/value pairs. An array is an ordered sequence of zero or more values. The values can be strings, numbers, booleans, null, and these two structured types.
Code example
Note : Here I am just conferring how to parse and how to convert JsonObject to Java Object, so that you could use it your live projects using selenium.
Application contentType : Json
JSON is an easier-to-use alternative to XML.
Example : You can see it here.
Objective : To validate Address : Chicago, IL, USA.
GoogleMaps API : http://maps.googleapis.com/maps/api/geocode/json?address=chicago&sensor=false
We can easily parse Json using “json-lib-2.4-jdk15.jar” – Download from here.
Please consider the following code as a reference:
import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Scanner; import org.json.JSONArray; import org.json.JSONObject; import org.testng.Reporter; import org.testng.annotations.Test; public class ReadJsonObject{ @Test public void aptTesting() throws Exception { try { URL url = new URL( “http://maps.googleapis.com/maps/api/geocode/json?address=chicago&sensor=false”); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(“GET”); conn.setRequestProperty(“Accept”, “application/json”); if (conn.getResponseCode() != 200) { throw new RuntimeException(” HTTP error code : ” + conn.getResponseCode()); } Scanner scan = new Scanner(url.openStream()); String entireResponse = new String(); while (scan.hasNext()) entireResponse += scan.nextLine(); System.out.println(“Response : “+entireResponse); scan.close(); JSONObject obj = new JSONObject(entireResponse ); String responseCode = obj.getString(“status”); System.out.println(“status : ” + responseCode); JSONArray arr = obj.getJSONArray(“results”); for (int i = 0; i < arr.length(); i++) { String placeid = arr.getJSONObject(i).getString(“place_id”); System.out.println(“Place id : ” + placeid); String formatAddress = arr.getJSONObject(i).getString( “formatted_address”); System.out.println(“Address : ” + formatAddress); //validating Address as per the requirement if(formatAddress.equalsIgnoreCase(“Chicago, IL, USA”)) { System.out.println(“Address is as Expected”); } else { System.out.println(“Address is not as Expected”); } } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
That’s it, now you know how to convert JsonObject to Java Object and use it in your Selenium snippet.
You can practice using API : http://restcountries.eu/rest/v1
Hello
I’m sorry but can you tell me where you have used selenium for Api Testing?
Hello vir.jsbot,
I do agree it’s plain Java code but if you notice the code, I’m validating ‘formatted_address’. Can’t we integrate this with Selenium API to test your application functionalities? You should be intelligent enough to use it your framework. Convert Json Objects to string and then store it in a collection which can be used at later point of time. Let me give you a hint
Scenario: I need to check the data published from dashboard (web app) should be displayed in mobile apps too.
What are we supposed to do?
This is just one of the examples to elucidate. My objective is to check the app functionality and at the same I’m testing Web API too. So integrating with selenium shouldn’t be useless.
Thanks & Regards
Charan
https://seleniumbycharan.wordpress.com/about/
First instead of all that work in plain Java I would use RestAssured for the Api requests. It works with the google Gson library for JSON manipulation and also has integrated Json path so you can access a specific json property directly without having to go through JSON Arrays and all that work.
I would also suggest integrating a build framework like maven in the project and not adding JAR files to your project in order to improve the portability of your project
As for “API Testing using Selenium” from what I understand from your response is that you want to test the integration between the api and the UI, which yes would require both api testing (using your pure Java code or something like RestAssured which I have recommended) and UI testing using Selenium but it does not mean that you are testing API using Selenium. I hope this does not sound to critical of your title but I do feel like your post is more about integrating API with UI testing.
The article is really informative to get started for the API testing.
I am using some tools that are available in the market for API testing e.g. Postman, Runscope. With these tools, the coding is negligible as compared to what has proposed above in the post. I can concentrate more on the logic or validation on the JSON/XML rather than writing code to for the requests GET or POST etc. Apart from this, I can schedule my API test cases to run automatically e.g. every hour or day.
I would like to know is there a benefit of testing API as shown in the post above compared to the tools available in the market such as Postman or Runscope etc.
Thanks
Charanjit