首页 > 解决方案 > 将 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)

谢谢,

马特

标签: javascriptgroovytimezonekatalon-studio

解决方案


要在 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)

推荐阅读