HTTP Post Example using Apache Http Client

Sending HTTP Requests using Apache HTTP Client:
Below is the sample code to test end points using Apache Http Client in Java
This is a POST Method.

package org.apache.http.examples.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;

public class PostLibrary {
	
	public static void main(String args[]) throws Exception {
		
		String url = "http://localhost/PublicAuthentication/";
		
		HttpClient client = HttpClientBuilder.create().build();
		HttpPost post = new HttpPost(url);	 
		// add header
		post.setHeader("Content-Type", "Application/JSON");
		//Compose JSON
		post.setEntity(new StringEntity("{\"username\":\"user@acs.com\", \"password\":\"password\"}"));
		//post.setEntity(new UrlEncodedFormEntity(urlParameters));	 
		HttpResponse response = client.execute(post);
		System.out.println("Response Code : " 
	                + response.getStatusLine().getStatusCode());	 
		BufferedReader rd = new BufferedReader(
		        new InputStreamReader(response.getEntity().getContent()));	 
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
		System.out.println(result);
	}

}
Advertisements

Sending HTTP Requests using Apache HTTP Client

Sending HTTP Requests using Apache HTTP Client:

Below is the sample code to test end points using Apache Http Client in Java
This is a GET Method.

package org.apache.http.examples.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

public class GetLibrary {
	
	public static void main(String args[]) throws Exception {
		String url = "http://www.google.com/search?q=httpClient";
		 
		HttpClient client = HttpClientBuilder.create().build();
		HttpGet request = new HttpGet(url);		
		request.addHeader("User-Agent", "USER-AGENT");
		HttpResponse response = client.execute(request);	 
		System.out.println("Response Code : " 
	                + response.getStatusLine().getStatusCode());	 
		BufferedReader rd = new BufferedReader(
			new InputStreamReader(response.getEntity().getContent()));	 
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
		System.out.println(result);
	}
}

SoapUI – Converting your functional tests into load tests

In the SoapUI – Getting Started we have seen how to create a functional test.

Now we are going to see how to do load tests for the API’s by reusing your functional tests that you have created.

Once you have created your functional tests, under TestCase tree, you will be having three child nodes.
one is test step where your functional test steps resides. Second is the Load Test node.

Right Cick on the Load Test Node and select “New Load Test”. This will automatically create the Load Tests Steps for you.

Load1

If you open the window, You can see some new terms or facts in the window. Lets see these facts one by one.

1. In the LoadTest tool bar buttons, you can see a Limit option by default sets to 60 seconds.
This is nothing but Setting the limit for the LoadTest Execution time.
2. Threads – Sets the number of threads/Virtual users to be used.
3. Strategy – Choose a LoadTest Strategy. Lets see this in detail. By default I will use Simple which means, TestCases will be executed within a configurable Test delay.
4. Test Delay – The time in milliseconds between each batch of requests.
5. Random – The random factor of the Test Load. This means by default the Test delay is 1000 ms and the random factor is 0.5.
So the threads will be distributed randomly between 500ms – 1000ms
6. min-The shortest response time the step has taken (in milliseconds).
7. max-The longest response time the step has taken (in milliseconds).
8. avg-The average response time for the test step (in milliseconds).
9. last-The last response time for the test step (in milliseconds).
10. cnt-The number of times the test step has been executed.
11. tps-The number of transactions per second for the test step.
12. bytes-The number of bytes processed by the test step.
13. bps-The bytes per second processed by the test step.
14. err-The number of assertion errors for the test step.
15. rat-Percentage of requests that failed

When clicking on the Run button, you can see the data/statistics for all the facts mentioned above.

Now we have also done performance tests for our API’s by re-using our existing functional tests.

Script Assertions in SoapUI

SoapUI uses XPath to manipulate XML. But we cannot use XPath expressions on JSON.
But soapUI have capability to convert JSON to XML.
Only difference is that instead of using Response property you have to use ResponseAsXml property.
ResponseAsXml in soapUI will convert JSON to XML.
The best and easy way to assert on a JSON response is to use a Groovy Script Assertion
Now lets see how to use Script Assertion on a JSON reponse.

"Token":    {
      "UserId": "test@test.com",
      "TimeStamp": "31/12/2014",
      "SignedInAs": "test"
   },

The following is the script we can use to assert the content of the above Json response

import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def slurper = new JsonSlurper()
def json = slurper.parseText response
assert json.Token.UserId = "test@test.com"
assert json.Token.TimeStamp == "31/12/2014"
assert json.Token.SignedInAs == "test"

Basic Assertions in SoapUI

1. Contains:
Search for the existence of a String in the Response Value. Applicable for JSON/XML reponses.

Assertion1

For Example if your response JSON is

"Success": true,
   "AUTH":    {
      "UserId": "linkeshkannavelu",
      "TimeStampUtc": "2014-04-22T07:25:05.0077957Z",
      "SignedAs": "4Rfc0/test/Vcpk="
   }

and you are looking for the string linkeshkannavelu in the response, then you can enter the string in the Assertion Window.

Assertion2

2. XPath Match:
Traverse the XML response and return the value presents in the specific XML Node and then compares it with the expected value given.
Applicable only to property in XML Format.

Assertion3

For Example, in the last post we have verified the title of the site http://linkeshkananvelu.com.
If the returned response is

<html>
	<head>
		<body>
			<title>Keep Software Testing Weird</title>
		</body>
	</head>
</html>

You can check the title of the page by using the following Xpath.

Assertion4

3. Not Contains
Search for the non existence of a String in the Response Value. Applicable for JSON/XML reponses.

Assertion5

For Example if your response JSON is

"Success": true,
   "AUTH":    {
      "UserId": "linkeshkannavelu",
      "TimeStampUtc": "2014-04-22T07:25:05.0077957Z",
      "SignedAs": "4Rfc0/test/Vcpk="
   }

and you are looking for the string TestUsername to be not present in the response, then you can enter the string in the Assertion Window.

Assertion6

If the String exists in the response, then the test will fail.

4. Valid HTTP Status Codes:
In the reponse, usually we will get a HTTP Status Code. We can assert these response codes also.

Assertion7

For example, if you are checking that your response message got the code HTTP Status 200, then you can assert the code by

Assertion8

5. Invalid HTTP Status Codes:
This is similar to Not Contains. If the HTTP Status Code that we are receiving Should not contain the list of Codes, then we can check those assertions using this.

Assertion9

For example, if you are checking that your response message should not have the code HTTP Status 401 and 404, then you can assert the response code by

Assertion10

These are the frequently used assertions in SoapUI.

SoapUI Getting Started

SoapUI is a free and open source cross-platform Functional Testing solution. With an easy-to-use graphical interface, and enterprise-class features,
SoapUI allows you to easily and rapidly create and execute automated functional, regression, compliance, and load tests.
Download SoapUI From http://sourceforge.net/projects/soapui/files/latest/download
Install this by double clicking on the downloaded file and simply following the steps. Now Open SoapUI.

My First Project in SoapUI:
Today We are going to create first project in SoapUI by sending simple HTTP Requests and verifying the Response.

1. After Opening SoapUI, Goto File and Click “New Rest Project”

SoapUI1

2. Enter the URL for the endpoint/Service that you are going to test and Click Ok. I have entered “http://linkeshkannavelu.com&#8221;
SoapUI2

3. This will create the “Rest Project 1” with the resource http://linkeshkannavelu.com
Right Click and delete all the Child Resources under http://linkeshkannavelu.com
4. Right Click the “Rest Project 1” and Select “New TestSuite”. Enter the name for the Test Suite as “MyTestSuite”

SoapUI3

5. Right Click on the “MyTestSuite” and Select “New TestCase”. Enter the name for the Test Case as “TestCase1”

SoapUI4

6. Under TestCase1, right click on “Test Steps(0)” and Select “Add Step” and Select “HTTP Test Request”.
7. Enter the Test Step Name and End Point and Give OK.

SoapUI5

8. Look at the following figure. The Method is “GET” and requested URL is http://linkeshkannavelu.com

SoapUI8

9. Now we are going to hit the Request and Verify the expected result with the actual.
To do this. we are going to insert “Assertions” here.
10. At the bottom of the Test Request screen, Click on the “Assertions” and Click on the + SYmbol to add an assertion for this test request.
11. Select the type of assertion as “Property Content” in the LHS and Click “Xpath Match”.

SoapUI9

12. Now we are going to Verify the title of the http response. Title of my site should be “Keep Software Testing Weird”

SoapUI6

13. Hit the Submit Request button at the top of the Test Request screen and see the response in response window.
As the Xpath matches with the actual response, My Test Step should Go Green and the Xpath Match Assertion should also Go Green.
It means, the Expected Result “Keep Software Testing Weird” matched with the actuals.

SoapUI7

Thats it. We Sent a request to a end point and got the required response and verified that.

Soap UI – Make JDBC Requests

To do the JDBC request from Soap UI, first we need to install the JDBC driver for the database we are using.

I am using SQL Server and so I have downloaded the JDBC driver for SQL server from here.

http://www.microsoft.com/en-in/download/details.aspx?id=11774

Extract the *.tar.gz file and copy the sqljdbc4.jar file.
Place this jar file under the “bin\ext\” directory where the SoapUI is installed in your machine.

C:\Program Files (x86)\SmartBear\SoapUI-4.6.4\bin\ext\

Now restart the Soap UI.[CLose and then Open]

Lets test this by creating a JDBC test Request.

1. Right Click on a test case and “Add Step” and clic “JDBC Request”
2. Give the driver name as com.microsoft.sqlserver.jdbc.SQLServerDriver
3. Specify the connection string as

jdbc:sqlserver://<servername>:1433;databaseName=<databasename>;user=<username>;password=<password>;

Click on the Test Connection Button.

You should get a prompt like “Connection Tested Successfully”.

Now you are all set to goto make JDBC requests.

Give a sample SQL query under “SQL Query” text area like SELECT * FROM tablename
Run the Request.

You can able to see the results in the xml format.