如何构建一个Dubbo接口测试的通用框架
从上面的流程我们可以看出,测试类大致的一个结构:
json文件的定义
{
"Connection": {
"URL": "101.219.255.73:50883",
"SERVICE_NAME": "com.company.mdapi.sdk.material.export.MaterialApiService",
"VERSION": "1.0.0",
"METHOD": "queryUnboundListByPage",
"HELPCLASS": "com.utils.common.helper.MaterialApiService.QueryUnboundListByPageHelper"
},
"Random": false,
"Args": {
"sourceSystem": 2,
"querySourceSystem": null,
"materialCode": "MD_S6006",
"materialName": null,
"materialType": null,
"pkId": null,
"shipperCode": "ZA01",
"storageCenterCode": "HZA1",
"pager": {
"page": 1,
"rows": 5,
"totalCount": null,
"pageOffset": null,
"sort": "ID",
"order": "ASC",
"totalPage": null,
"pageCode": 7,
"startPageIndex": null,
"endPageIndex": null,
"previewPage": null,
"nextPage": null
}
},
"Verify": false
}
参数具体定义:
Java程序实现数据转换及接口调用
public class AddMaterialListHelper extends SampleHelper>> {
public static final String[] RANDOM_FIELD = {"materialCode","materialName"};
@Override
public Map readJsonFile(String jsonPath) {
JsonParser parser = new JsonParser();
try {
JsonObject json=(JsonObject) parser.parse(new FileReader(jsonPath));
Map values = new HashMap();
UtilsHelper.getInstance().getConnectionArgument(values, json);
JsonObject args=json.get("Args").getAsJsonObject();
if (!args.get("data").isJsonNull()) {
String jsonArray = args.get("data").getAsJsonArray().toString();
//TODO
Gson gson = new Gson();
@SuppressWarnings("serial")
List dtoList = gson.fromJson(jsonArray,
new TypeToken>() {
}.getType());
RandomNum.setRandom(json , RANDOM_FIELD , dtoList);
values.put("data", dtoList);
}
if (!args.get("sourceSystem").isJsonNull()) {
values.put("sourceSystem", new Integer(args.get("sourceSystem").getAsInt()));
}
return values;
} catch (JsonIOException e) {
e.printStackTrace();
} catch (JsonSyntaxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
@Override
public Result> callRemoteMethod(Object object, Map values) {
MaterialInterfaceService service = (MaterialInterfaceService) object;
@SuppressWarnings("unchecked")
Result> callResult = service.addMaterialList (
(int) values.get("sourceSystem"),
(List) values.get("data"));
return callResult;
}
}
public class MaterialInterfaceDTO implements Serializable {
private static final long serialVersionUID = -3725469669741557392L;
private String materialCode;
private String materialName;
private Integer materialType;
private Integer importFlag;
private String sixNineCode;
private Long expirationDate;
private Long packingSpecification;
private String basicUnit;
private String minSaleUnit;
private String basicUnitName;
private String minSaleUnitName;
private String materialImageUrl;
private Integer transportFlag;
private Integer sourceSystem;
private String createName;
private String updaterName;
public MaterialInterfaceDTO() {
}
public String getMaterialCode() {
return this.materialCode;
}
public void setMaterialCode(String materialCode) {
this.materialCode = materialCode;
}
public String getMaterialName() {
return this.materialName;
}
public void setMaterialName(String materialName) {
this.materialName = materialName;
}
public Integer getMaterialType() {
return this.materialType;
}
package com.utils.common;
import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import java.util.Map;
public class RunMethodTest extends AbstractJavaSamplerClient {
private static String JMX_PATH = null;
private static String TAG = Thread.currentThread().getStackTrace()[1].getClassName();
private SampleHelper helper = null;
private Map values = null;
private Map config = UtilsHelper.getInstance().getConfigProperties();
private String ARGS_FILE;
private Object object;
public void setupTest(){
//定义测试初始值,setupTest只在测试开始前使用
System.out.println("setupTest");
}
public void init() {
// 当前应用配置
ApplicationConfig application = new ApplicationConfig();
application.setName(TAG);
// 获取具体参数配置路径
if ("true".equals(config.get("DEBUG").toString())) {
JMX_PATH = ARGS_FILE;
} else {
JMX_PATH = UtilsHelper.getInstance().getScriptPath(config.get("SCRIPT_HOME").toString(), ARGS_FILE);
}
Map helpArgs = UtilsHelper.getInstance().getHelpClassAndMethod(JMX_PATH);
helper = (SampleHelper)UtilsHelper.getInstance().invokeStaticMethodByReflect(
(String) helpArgs.get("HELPCLASS"),
(String) helpArgs.get("HELPMETHOD")
) ;
values = helper.readJsonFile(JMX_PATH);
// 注意:ReferenceConfig为重对象,内部封装了与注册中心的连接,以及与服务提供方的连接
// 引用远程服务,配置dubbo服务版本、服务名称、url地址
ReferenceConfig reference = new ReferenceConfig(); // 此实例很重,封装了与注册中心的连接以及与提供者的连接,请自行缓存,否则可能造成内存和连接泄漏
reference.setApplication(application);
reference.setTimeout(20000);
reference.setVersion(values.get("conn_version").toString());
reference.setInterface(values.get("conn_service_name").toString());
reference.setUrl(values.get("conn_url").toString());
// 和本地bean一样使用xxxService
object = reference.get(); // 注意:此代理对象内部封装了所有通讯细节,对象较重,请缓存复用\
}
public SampleResult runTest(JavaSamplerContext arg0) {
SampleResult sr = new SampleResult(); ;
try {
//获取参数
ARGS_FILE = arg0.getParameter("ARGS_FILE");
//dubbo初始化
init();
//jmeter结果对象
// sr.setSampleLabel(TAG);
sr.sampleStart();
sr.setSuccessful(true);
String res = helper.handleResult(helper.callRemoteMethod(object, values));
sr.sampleEnd(); // jmeter 结束统计响应时间标记
if (res != null) {
JsonObject response = new JsonParser().parse(res).getAsJsonObject();
System.out.println("\n*************测试返回值****************\n");
System.out.print(response.toString()+"\n");
if (response.get("code").getAsInt() != 0) {
sr.setSuccessful(false);
}
sr.setResponseData(response.toString(), "UTF-8");
// if (null != response.get("data")) {
// sr.setResponseData(response.get("data").toString(), "UTF-8");
// System.out.print(response.get("data").toString()+"\n");
// } else if (null != response.get("result")) {
// sr.setResponseData( response.get("result").toString(), "UTF-8");
// }
} else {
System.out.print("handleResult return null\n");
}
} catch (Exception e) {
e.printStackTrace();
sr.setResponseCode("999");
sr.setResponseMessage(e.getMessage());
sr.setSuccessful(false);
}
return sr;
}
public Arguments getDefaultParameters(){
//参数定义,显示在前台,也可以不定义
Arguments params = new Arguments();
params.addArgument("ARGS_FILE", "");
return params;
}
public void teardownTest(JavaSamplerContext arg0){
super.teardownTest(arg0);
}
}