Xml – Groovy Script – Automatic Request and saving response from SOAP UI

groovysoapsoapuixml

I am new to Groovy scripting.

Requirement To read the request values from a text file and pass it to the soap request xml and save the output.

Issue facing: I am not able to read the data from step 1 to step 2. However I am setting the values in context variable as well. Kindly help me to fix the issue so that I can able to automate the entire process.

Note: We have only access to SOAPUI not SOAPUI Pro

Step 1:

File file1 = new File("C:\\Users\\Groovy Test\\requests\\orders.txt") 
List textLine = file1.readLines() 
log.info textLine 
context.put('textLine', textLine)  
log.info textLine

Step 2:

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header>
</soapenv:Header>
<soapenv:Body>
<OrderId>${context.get('textLine' )}</OrderId>
</soapenv:Body>
</soapenv:Envelope>

Step 3:

def fileList = context.get('textLine')
def fileName = fileList.pop()
def newname = fileName[0..-5]
def response = context.expand( '${Step2#Response}' )
def f = new File("C:\\Users\\Groovy Test\\responses\\${fileName}_Response.xml")
f.write(response, "UTF-8")
if(fileList.size() >0)
{
testRunner.gotoStepByName("Step2")
}

Best Answer

Here is the approach to achieve what you are looking for.

The test case contains 3 steps as shown below:

  • step1 - Groovy Script test step. This reads data source, executes order steps by looping thru it. Controls test run.
  • step2 - Soap Request test step. Gets orders & saves response.
  • step3 - Groovy Script test step. A way to exit the test execution.

Step1

Groovy Script for step1:

def data = new File('C:/Users/Groovy Test/requests/orders.txt') 
data.eachLine { orderId ->
   context.orderId = orderId
   //Get the step2, index of the step is 1
   def step = context.testCase.getTestStepAt(1)
   //Run the step2
   step.run(testRunner, context)
}
//By now all the orders got executed, now need to exit the step without additionally running step2
//So, jump to step2, index is 2
testRunner.gotoStep(2)

Step2

Change the request to use <OrderId>${orderId}</OrderId>

Add Script Assertion for the request of step2. This checks the response and saves it.

Script Assertion for step2

//Check if there is response
assert context.request, "Request is empty or null"

//Save the contents to a file
def saveToFile(file, content) {
    if (!file.parentFile.exists()) {
         file.parentFile.mkdirs()
         log.info "Directory did not exist, created"
    }
    file.write(content) 
    assert file.exists(), "${file.name} not created"
}

def f = new File("C:/Users/Groovy Test/responses/${context.orderId}_Response.xml")
saveToFile(f, context.response)

Step3

Groovy Script for step3:

log.info "Test completed."
Related Topic