我在响应中有两个字段,其中有两个参数作为响应。 { date1:“ 2018年12月18日”, date2:“ 23-11-2018” }
我要测试id date1小于今天的日期 并且date2小于请求参数中的其他日期。 我不知道如何在空手道模式验证中执行此操作
答案 0 :(得分:2)
您需要将字符串date解析为java date / long
* def toTime =
"""
function(s) {
var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
var sdf = new SimpleDateFormat("dd-MM-yyyy");
return sdf.parse(s).time
}
"""
* def other = "20-11-2018"
* def today = new java.util.Date().time
* def response = { date1: "18-12-2018", date2: "23-11-2018" }
* assert today > toTime(response.date1)
* assert toTime(other) < toTime(response.date2)
答案 1 :(得分:0)
作为彼得·托马斯的答案的附录。这是我将其外部化为可调用的.feature文件的方法:
@ignore
Feature: Reusable function to capture info about the date
# Example:
# * def dateResponse = call read('classpath:features/test_getdate.feature')
# * def todaysDate = dateResponse.today
# * def lastYearDate = dateResponse.oneYearAgo
Background: Setup
* def pattern = 'MM/dd/yyyy'
* def getDate =
"""
function() {
var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
var sdf = new SimpleDateFormat(pattern);
var date = new java.util.Date();
return sdf.format(date);
}
"""
Scenario: Capture todays date
* def today = getDate()
* karate.log("Today's date is: " + today )
Scenario: Capture a year old date
* def today = getDate()
* def getSubtractedYear =
"""
function(s) {
var DateTimeFormatter = Java.type("java.time.format.DateTimeFormatter");
var LocalDate = Java.type("java.time.LocalDate");
var ChronoUnit = Java.type("java.time.temporal.ChronoUnit");
var dtf = DateTimeFormatter.ofPattern(pattern);
try {
var adj = LocalDate.parse(today, dtf).minusMonths(12);
return dtf.format(adj);
} catch(e) {
karate.log('*** date parse error: ', s);
}
}
"""
* def oneYearAgo = getSubtractedYear()
* karate.log("One year ago is: " + oneYearAgo)
然后我像这样测试它:
@mysuite
Feature: Get information about the date
Background: Setup
* def dateResponse = call read('classpath:features/test_getdate.feature')
Scenario: Extract todays date
* def todaysDate = dateResponse.today
* karate.log("Captured todays date: " + todaysDate)
Scenario: Extract last years date
* def lastYearDate = dateResponse.oneYearAgo
* karate.log("Captured last years date: " + lastYearDate)