user5653362 user5653362 - 28 days ago 15
Groovy Question

Read from file and save in Property using groovy script

I am trying to read two values from a text file both values on a different line

for example:

1234

5678

This is what I tried:

def f = new File('/testdata.txt')
def records = f.readLines();

records.each {
testRunner.testCase.setPropertyValue("IdOne",it)
testRunner.testCase.setPropertyValue("IdTwo",it)

}


But it is only setting the last value to both custom properties.

Answer

The problem is that your loop iterates two times, the first it assigns the first value to your IdOne and IdTwo properties, the second iteration overwrites both properties with the second value; due to this you've the last iteration value in your both properties. A possible solution as @user1708042 notes in the comments could be simply not iterate and set the values for your properties directly:

def f = new File('/testdata.txt') 
def records = f.readLines()
testRunner.testCase.setPropertyValue("IdOne",records[0])     
testRunner.testCase.setPropertyValue("IdOne",records[1])

Another possible solutions could be to combine two lists; one with the property names and other one with the values in a Map, and then iterate over map entries setting the property name and the property values, for example:

def propertyName = ['IdOne','IdTwo']
def records = ['1234','5678'] // def records = new File('/testdata.txt').readLines()

def mapProperties = [propertyName,records].transpose().collectEntries()

mapProperties.each{ name, value ->
    testRunner.testCase.setPropertyValue(name,value)     
}