接口测试之使用httpClient提交post请求

实例需求:测试系统间订单推送接口功能

提交请求并获取服务器回响报文

创建getOrderPushStatus.java

package hna.mianshui365;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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.testng.annotations.Test;
import java.io.BufferedReader;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * 发送请求
 * 
 * @author Jimmy Lee
 * @version 1.0 2017/2/9
 * @return 返回响应报文
 **/

public class getOrderPushStatus {
	private String url = null;

	public String geturl() {
		return url;
	}

	public String getHttpRespone(String orderNumber) {
		String httpResults = null;
		url = ("http://10.167.7.56:20881/order/push");
		String params = "{\"body\":{ \"inParams\": [ { \"orderSn\": \"" + orderNumber + "\" }]}}";
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httppost = new HttpPost(url);
		CloseableHttpResponse response = null;
		try {
			httppost.addHeader("Content-type", "application/json; charset=utf-8");
			httppost.setHeader("Accept", "application/json");
			StringEntity requestEntity;
			requestEntity = new StringEntity(params, "utf-8");

			httppost.setEntity(requestEntity);
			//System.out.println("executing request " + httppost.getURI());
			response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				httpResults = EntityUtils.toString(entity, "UTF-8");
				//System.out.println("--------------------------------------");
				//System.out.println("Response content: " + httpResults);
				//System.out.println("--------------------------------------");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {

				httpclient.close();
				if (response != null) {
					response.close();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return httpResults;
	}
}

需要一个可根据字符串对象获取JSON键名所对应的值的方法

创建Common.java

package hna.mianshui365;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 解析Json内容
 * 
 * @author Jimmy Lee
 * @version 1.0 2017/2/9
 * @return JsonValue 返回JsonString中JsonId对应的Value
 **/

public class Common {
    public static String getJsonValue(String JsonString, String JsonId) {
        String JsonValue = "";
        if (JsonString == null || JsonString.trim().length() < 1) {
            return null;
        }
        try {
            JSONObject obj1 = new JSONObject(JsonString);
            JsonValue = (String) obj1.getString(JsonId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return JsonValue;
    }
}

创建OrderPushStatusTest.java测试用例:

package hna.mianshui365;

import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import java.io.IOException;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.Reporter;

/**
 * 测试用例
 * 
 * @author Jimmy Lee
 * @version 1.0 2017/2/9
 **/

public class OrderPushStatusTest{
	public String httpResult = null;
	public String head = null;
	public String headinfo = null;
	public String outParams = null;
	public String returnCode = null;
	public String bodyinfo = null;
	public String msg = null;
	public String exp_returnCode = null;
	public String exp_msg = null;
	public String orderNumber = null;
	public static getOrderPushStatus orderpushstatus = new getOrderPushStatus();
	
	@Parameters({ "orderNumber" })
	@Test
	public void getOrder(String orderNumber) throws IOException{
		exp_returnCode = "000000";
		exp_msg = "推送成功";
		System.out.println("dayingdeshi"+ orderNumber);
		Reporter.log("请求传入订单号"+orderNumber+"开始推送");
		httpResult = orderpushstatus.getHttpRespone(orderNumber);
		Reporter.log("请求地址:"+orderpushstatus.geturl());
		Reporter.log("返回结果: "+httpResult);
		
		JSONObject resultJsonObject = new JSONObject(httpResult);
		JSONObject headinfoObject= new JSONObject(resultJsonObject.get("head").toString());
		headinfo = headinfoObject.toString();
		returnCode = Common.getJsonValue(headinfo,"returnCode");
		Reporter.log("returnCode返回的预期结果:" + exp_returnCode + ",returnCode返回的实际结果:" + returnCode);
		Assert.assertEquals(returnCode,exp_returnCode);

		JSONObject body= new JSONObject(resultJsonObject.get("body").toString());
		JSONArray outParamsArray=new JSONArray(body.get("outParams").toString());
		outParams = outParamsArray.get(0).toString();
		msg = Common.getJsonValue(outParams,"msg");
		Reporter.log("msg返回的预期结果:" + exp_msg + ",msg返回的实际结果:" + msg);
		Assert.assertEquals(msg,exp_msg);

	}
	
	
}

pom.xml配置

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>hna</groupId>
	<artifactId>mianshui365</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>mianshui365</name>
	<url>http://maven.apache.org</url>

	<!-- maven 引用远程库 -->
	<repositories>
		<repository>
			<id>java-net</id>
			<url>http://download.java.net/maven/2</url>
		</repository>
	</repositories>

	<!-- maven 参数配置,这里引用不同的testng.xml -->
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<xmlFileName>testng.xml</xmlFileName>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.3</version>
		</dependency>
		<!-- 依赖testNg -->
		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<version>6.10</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.google.inject</groupId>
			<artifactId>guice</artifactId>
			<version>4.0</version>
		</dependency>

		<!-- 依赖reportNg 关联testNg -->
		<dependency>
			<groupId>org.uncommons</groupId>
			<artifactId>reportng</artifactId>
			<version>1.1.4</version>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.testng</groupId>
					<artifactId>testng</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<!-- 依赖Guice -->
		<dependency>
			<groupId>com.google.inject</groupId>
			<artifactId>guice</artifactId>
			<version>4.0</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>velocity</groupId>
			<artifactId>velocity-dep</artifactId>
			<version>1.4</version>
		</dependency>

		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>20160810</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<!-- 添加插件 关联testNg.xml -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.17</version>
				<configuration>
					<suiteXmlFiles>
						<suiteXmlFile>res/${xmlFileName}</suiteXmlFile>
					</suiteXmlFiles>
				</configuration>
			</plugin>

			<!-- 添加插件,添加ReportNg的监听器,修改最后的TestNg的报告 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.5</version>
				<configuration>
					<properties>
						<property>
							<name>usedefaultlisteners</name>
							<value>false</value>
						</property>
						<property>
							<name>listener</name>
							<value>org.uncommons.reportng.HTMLReporter,org.uncommons.reportng.JUnitXMLReporter</value>
						</property>
					</properties>
					<workingDirectory>target/</workingDirectory>
					<forkMode>always</forkMode>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>
	

testng.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestNG 项目报告">
	<parameter name="orderNumber" value="2017020800907" />
	
	<test name="Test">
		<classes>
			<class name="hna.mianshui365.OrderPushStatusTest" />
		</classes>
	</test> <!-- Test -->
	
<listeners>

<listener class-name="org.uncommons.reportng.HTMLReporter" />

<listener class-name="org.uncommons.reportng.JUnitXMLReporter" />

</listeners>
	
</suite> <!-- Suite -->

生成TestNG接口测试报表:

194642_s5yZ_2436189.png

转载于:https://my.oschina.net/jimmylee216/blog/835009

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值