You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写JMeter日期递增自定义函数及设计对应测试计划?

JMeter测试计划设计与日期自动递增实现

一、测试计划设计步骤

  • 线程组配置:设置线程数为30,Ramp-Up时间设为0(若需同时发起所有请求),循环次数设为1,确保每个线程仅执行一次请求。
  • 通用参数配置:添加「HTTP请求默认值」元件,填入目标服务器的地址、端口等通用信息,减少重复配置。
  • 请求参数设置:添加「HTTP请求」元件,在需要传入日期的参数位置,引用后续生成的日期变量,比如参数名设为date,参数值填${targetDate}。
  • 结果监控:添加「查看结果树」「聚合报告」等监听器,用于查看请求响应内容和统计测试数据。

二、日期自动递增实现方案

方案1:JMeter内置函数快速实现

直接在HTTP请求的参数值中写入组合函数,自动生成对应日期并存入变量:

${__javaScript(new Date(new Date().getFullYear(), new Date().getMonth(), ${__threadNum()}).toISOString().split('T')[0], targetDate)}
  • 逻辑说明:__threadNum()获取当前线程编号(1-30),以此作为当月的日期天数;通过new Date()构造对应日期,转成YYYY-MM-DD的标准格式后,将结果存入targetDate变量供请求使用。

方案2:JSR223预处理器(更灵活,推荐)

在HTTP请求前添加「JSR223预处理器」,选择Groovy语言(性能优于JavaScript),编写代码实现日期生成:

// 获取线程编号(JMeter线程索引从0开始,+1后对应1-30号日期)
def threadNum = ctx.getThreadNum() + 1
def currentMonth = new Date()
// 构造当月对应天数的日期
def targetDate = new Date(currentMonth.year, currentMonth.month, threadNum)
// 格式化为YYYY-MM-DD字符串
def formattedDate = targetDate.format("yyyy-MM-dd")
// 将日期存入变量,供请求引用
vars.put("targetDate", formattedDate)

额外优化:处理小月天数不足的情况

如果遇到当月天数少于30的情况(如2月、4月等),可以在Groovy代码中添加判断,避免生成无效日期:

def threadNum = ctx.getThreadNum() + 1
def currentMonth = new Date()
// 获取当月最后一天的日期数
def lastDayOfMonth = new Date(currentMonth.year, currentMonth.month + 1, 0).date

if (threadNum > lastDayOfMonth) {
    // 可根据需求处理超出的线程,比如设为空字符串或跳至下月
    vars.put("targetDate", "")
} else {
    def targetDate = new Date(currentMonth.year, currentMonth.month, threadNum)
    def formattedDate = targetDate.format("yyyy-MM-dd")
    vars.put("targetDate", formattedDate)
}

内容的提问来源于stack exchange,提问作者Nazmul Hossain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 17:40:47