Testing server side automation using Java and JSON requests
I haven't tested automation before, only jUnit testing, now I have a request for this. But the automation is not on frontend using Selenium or so, it is easier than using JSON requests. I understand the principles of this, but don't know how to do it programmatically correctly. I have to make a payment request to the server and see if the answer is correct, not just the code, but the details of the response.
So far I have been doing the server request part, now when I get the response, what's the best way to compare or test it or how can I see if everything is correct? can you point me in the right direction?
source to share
If I understand your requirement correctly, then:
- First check what is the request and response format.
- As you said its JSON, you can easily do it with JAVA. Use java package - org.json.JSONObject to create request and validate JSON format.
-
You can send a request and get a response with this simple code:
CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet GetRequest = new HttpGet("ServerURL"); CloseableHttpResponse response = httpclient.execute(GetRequest);
use packages: import org.apache.http.impl.client.CloseableHttpClient;
you may also need to download apache - httpClient jar.
-
Once you get the answer, read it with the help of some reader, for example:
BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent()));
-
Convert this answer to a string, for example:
String line = ""; StringBuffer result = new StringBuffer(); while ((line = rd.readLine()) != null) { result.append(line); }
-
Finally, you have a string response, this can be parsed using the java package - org.json.JSONObject. Parse the JSON response as:
JSONObject js = new JSONObject(hudsonRTBObjectJSONString);
Hope it helps
source to share