Groovy script - help required
I have a groovy script, within which I'm trying to set some test properties i.e. today, tomorrow etc.... For one of the properties 'tommorowmonth' I need to work out the month, then use that result to lookup up a value from a list. This is so I can use the derived value later in tests as assertions against REST response.
My code works when I hardcode the month value, but returns an error when I try to pass it in as a variable. As follows:
Working code with hardcoded month = 9, this returns '1324'
use(groovy.time.TimeCategory) {
def now = new Date();now.format("yyyy-MM-dd")
def tomorrow = now + 1.day
def todayplus3m1d = now + 3.month + 1.day
def tomorrowday = now + 1.day; tomorrowday.format("d")
def tomorrowmonth = now + 1.day; tomorrowmonth.format("M")
def map = [1: '1316', 2: '1317', 3:'1318', 4:'1319', 5:'1320', 6:'1321', 7:'1322', 8:'1323', 9:'1324', 10:'1325', 11:'1326', 12:'1327']
//def tm = tomorrowmonth.format("M")
def item = map.find {key, value -> key==9} //this works with a hardcoded value
//def item = map.find {key, value -> key==tomorrowmonth.format("M")} //this doesn't work and return the error below
log.info item.value
Error code with variable month = tomorrowmonth.format("M"), this returns an error '
Java.lang.NullPointerException: Cannot get property ‘value’ on null object error at line 1
'
use(groovy.time.TimeCategory) {
def now = new Date();now.format("yyyy-MM-dd")
def tomorrow = now + 1.day
def todayplus3m1d = now + 3.month + 1.day
def tomorrowday = now + 1.day; tomorrowday.format("d")
def tomorrowmonth = now + 1.day; tomorrowmonth.format("M")
def map = [1: '1316', 2: '1317', 3:'1318', 4:'1319', 5:'1320', 6:'1321', 7:'1322', 8:'1323', 9:'1324', 10:'1325', 11:'1326', 12:'1327']
def item = map.find {key, value -> key==tomorrowmonth.format("M")}
log.info item.value
Any help appreciated.
I believe the error is because the format method returns a string, whilst the key of your map is an integer. The following code should give you what you require:
use(groovy.time.TimeCategory) { def now = new Date();now.format("yyyy-MM-dd") def tomorrow = now + 1.day def todayplus3m1d = now + 3.month + 1.day def tomorrowday = now + 1.day; tomorrowday.format("d") def tomorrowmonth = now + 1.day; tomorrowmonth.format("M") def map = [1: '1316', 2: '1317', 3:'1318', 4:'1319', 5:'1320', 6:'1321', 7:'1322', 8:'1323', 9:'1324', 10:'1325', 11:'1326', 12:'1327'] def item = map.find {key, value -> key==tomorrowmonth.format("M").toInteger()} log.info item.value }
I've only amended the map.find line, note the call to the method "toInteger()" on the result of the format method.