将 JavaScript 转换为 Groovy/Java

2024-02-03

我有一些 javascript 代码(Postman)需要转换以便在另一个 API 测试工具(Katalon)中使用。我在更新具有时区差异的日期时遇到错误。

尝试使用 TZ 差异更新预期日期时会发生错误。

原始 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)

Thanks,

Matt


要在 Katalon Studio 中运行 JS 代码,您可以使用 JavaScriptExecutor https://docs.katalon.com/katalon-studio/docs/webui-execute-javascript.html#description-:

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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 JavaScript 转换为 Groovy/Java 的相关文章

随机推荐