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

如何在Karate中等待数据库表状态从wait变更并校验测试结果

Karate测试:等待批处理任务完成并校验最终状态

你的需求是发送REST API消息后,等待批处理任务(30秒-1分钟)将数据库表test3中的状态从wait更新为Success或failed,并根据最终状态判断测试用例是否通过。以下是优化后的实现代码,替换了不可靠的固定休眠,改用Karate内置的轮询机制来确保状态更新完成:

* url apiurl
And request data
When method POST
Then status 200

# 校验test1表数据
* def id11 = db.readRows('select id1, payload1 from test1 where id = \'' + response + '\'')
And match id11.id1 == response
And match id11.payload1 == data

# 校验test2表数据
* def id22 = db.readRows('select id2, msg2 from test2 where id2 = \'' + response + '\'')
And match id22.id2 == response

# 轮询查询test3表的最终状态,直到状态变为Success/failed或超时(设置为90秒足够覆盖30-60秒的批处理时间)
* def getFinalStatus =
"""
function() {
  var result = dba.readRows('select status from test3 where final_id = \'' + response + '\'');
  return result.length > 0 ? result[0].status : null;
}
"""
* def finalStatus = waitUntil(90000, 5000, getFinalStatus)
# 断言状态必须为Success,否则测试用例失败
And match finalStatus == 'Success'

Examples:
  | read('data.json') |

关键优化点说明

  • 替换固定休眠为轮询:用waitUntil方法每隔5秒查询一次状态,最多等待90秒,避免固定休眠时间不足或过长的问题
  • 精准查询目标数据:原来的select top 1 ... order by final_id desc可能会取到其他数据,改为根据API返回的response(业务ID)查询对应记录,确保校验的是当前测试用例产生的数据
  • 明确状态断言:直接用match finalStatus == 'Success',如果状态是failed,这个断言会失败,测试用例自然不通过

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 01:52:45