javascript - 将 JavaScript 转换为 Groovy/Java
问题描述
我有一些 javascript 代码 (Postman) 需要转换才能在另一个 API 测试工具 (Katalon) 中使用。使用时区差异更新日期时出现错误。
尝试使用 TZ 差异更新 expectedDate 时发生错误。
原始 Javascript
//Postman - Validate Date
/*var jsonData = pm.response.json();
var expectedDate = new Date();
var firstDate = new Date(jsonData[0].Date);
var locationOffset = Number(pm.environment.get("locationOffset"));
var tzDifference = locationOffset * 60 + expectedDate.getTimezoneOffset();
expectedDate = new Date(expectedDate.getTime() + tzDifference * 60 * 1000);
firstDate = new Date(firstDate.getTime() + tzDifference * 60 * 1000);
pm.test("Testing Date - Expected: " + expectedDate + " & Returned: " + firstDate, function (){
pm.expect(firstDate.getDate()).to.be.eql(expectedDate.getDate());
});*/
已转换
import java.text.SimpleDateFormat
//get expected date
Date expectedDate = new Date()
println('ExpDate: ' + expectedDate)
//get first date
String newDateAdded = parsedJson.DailyForecasts[0].Date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM- dd'T'HH:mm:ss")
Date firstDate = dateFormat.parse(newDateAdded)
println("FirstDate: " + firstDate)
//get offset
def locationOffset = GlobalVariable.gmt_offset.toDouble() //gmt_offset = -4
//get TZ difference
def tzDifference = locationOffset * 60 + expectedDate.getTimezoneOffset()
println("tzDifference: " + tzDifference)
//update exp date (error here: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.util.Date(java.lang.Double)
expectedDate = new Date(expectedDate.getTime() + tzDifference * 60 * 1000)
println('ExpDate: ' + expectedDate)
//update first date
firstDate = new Date(firstDate.getTime() + tzDifference * 60 * 1000)
错误:groovy.lang.GroovyRuntimeException:找不到匹配的构造函数:java.util.Date(java.lang.Double)
谢谢,
马特
解决方案
要在 Katalon Studio 中运行 JS 代码,您可以使用 JavaScript Executor:
String postman ='''
var jsonData = pm.response.json();
var expectedDate = new Date();
var firstDate = new Date(jsonData[0].Date);
var locationOffset = Number(pm.environment.get("locationOffset"));
var tzDifference = locationOffset * 60 + expectedDate.getTimezoneOffset();
expectedDate = new Date(expectedDate.getTime() + tzDifference * 60 * 1000);
firstDate = new Date(firstDate.getTime() + tzDifference * 60 * 1000);
pm.test("Testing Date - Expected: " + expectedDate + " & Returned: " + firstDate, function (){
pm.expect(firstDate.getDate()).to.be.eql(expectedDate.getDate());
});
'''
WebUI.executeJavaScript(postman, null)
推荐阅读
- java - 播放 sbt dist 命令卡住
- python - 从数组中获取整数作为python中的单独变量
- node.js - 如何在 puppeteer 中将 URL 添加到 Flash 白名单
- javascript - 查询 MongoDB 以返回最近的 5 条记录(Mongoose 框架)
- android - 打开谷歌身份验证器应用
- python - 类型对象“专辑”没有属性“对象”
- wordpress - WordPress 上的 Recaptcha 不起作用
- reactjs - React Native - 用于动画问卷的 Scrollview 或 Flatlist
- sql-server - SQL Server:将数据库中的每个错误捕获到错误表中
- jquery - Ajax GET 发送空数据