Jmeter编写自定义函数

前言:打开jmeter函数助手,我们可以看到,jmeter已经封装好了很多实用的函数,但是有时候,这些函数也并不能完全满足我们实际的测试所需,jmeter的魅力所在就是它的开放性,这个时候我们可以自己封装所需的函数。


1.进到目录src\functions\org\apache\jmeter\functions,可以看到已有的函数:


2.新增类,继承抽象类AbstractFunction,其他不多说了,直接上代码:

/**
 * 根据年月日,时分秒返回单位为ms的时间戳
 * @author ljl
 */
public class DateWithTime extends AbstractFunction {
 
	private static final List<String> desc = new LinkedList<>();
	private static final String KEY = "__DateWithTime"; // 函数key,用于界面上选择函数

	static {
		desc.add(JMeterUtils.getResString("Date:yyyy-MM-dd")); // 函数助手中显示的参数说明,对应到参数
		desc.add(JMeterUtils.getResString("Time:HH:mm:ss"));
		desc.add(JMeterUtils.getResString("function_name_paropt"));// 保存函数返回结果的变量,用于引用
	}      
	private CompoundVariable varName, date, time;

	
	@Override
	public List<String> getArgumentDesc() {
		return desc;
	}

	public DateWithTime() {
	}

	// 函数执行,返回结果
	@Override
	public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException {
		String dataTemp = date.execute().trim();
		String timeTemp = time.execute().trim();
		String data_time = dataTemp + timeTemp;
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
		Date date = null;
		try {
			date = sdf1.parse(data_time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String varTime = date.getTime() + "";
		if (varName != null) {
			JMeterVariables vars = getVariables();
			final String varTrim = varName.execute().trim();
			if (vars != null && varTrim.length() > 0) {
				vars.put(varTrim, varTime);//
			}
		}
 
		return varTime;

	}

	/** {@inheritDoc} */
	// 接收参数
	@Override
	public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException {
		// 检查参数数量
		checkParameterCount(parameters, 2, 3);
		Object[] values = parameters.toArray();

		date = (CompoundVariable) values[0];
		time = (CompoundVariable) values[1];
		if (values.length > 2) {
			varName = (CompoundVariable) values[2];
		} else {
			varName = null;
		}
	}

	@Override
	public String getReferenceKey() {
		return KEY;
	}	
}
3.保存后运行,打开函数助手,可以看到以我们代码中设置的KEY为__DateWithTime的函数,如图:

使用效果:

调用该函数


运行结果:将2017-04-05 2:00:00转为ms时间戳


  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值