In this tutorial, we will learn how to write basic groovy script in SoapUI. We will learn about different types of operators that can be used in Groovy scripts in SoapUI.
Let’s begin with groovy scripting and how we can use it in SoapUI Pro.
This is the 6th tutorial in our SoapUI free online training series.
Table of Contents:
How To Write Groovy Script in SoapUI
SoapUI Groovy Script Test steps
Groovy Script test steps are included for custom automation test script creation in SoapUI / Pro. It can be used for functional/ load/regression.
Groovy is a scripting language which internally includes all the Java libraries, therefore all java related keywords and functions can be used in the groovy script directly. The Java libraries come with SoapUI and are integrated during the SoapUI Pro installation itself.
Here is how Groovy script can be added to a test:
Step #1. In SoapUI Pro create a SOAP project with valid WSDL document. Under the project, create a test suite with the desired name. Inside the test suite, add groovy script test steps as shown below:
Step #2. Enter the name of the step in the dialogue that comes up below and Click OK
Step #3. An editor where you can write your script is displayed. Alternately, you can double click on the groovy step name from your test case (Groovy step is the one that has a star prefix to it).
(Click on the image for an enlarged view)
For example: Let us write a simple script that shows a message in the log. Here is the one line script.
log.info ”soapUI script”
Step #4. To execute the above script in SoapUI Pro, click on the Run icon and see the results in the Log Output section.
A few points
- Test script execution: When the run button inside the groovy editor is clicked, the code inside the groovy step will only get executed. On the other hand, when the Run button is clicked for the entire test case, all the steps are executed in an order.
- This way any kind of programming can be done to the test scripts to add validations as required.
- There can be any number of groovy test steps to a test case.
- With a Groovy script, it is not required to compile and interpret separately to execute the code like other programming languages such as C, C++, Java, etc.
- Steps can be enabled or disabled inside the test suite using the comment feature. To do so, use the following:
// – indicates single line comment and
/* <some script> */ – denotes multi-line comment
Arithmetic Operations
All of the below can be performed in the groovy step editor:
/* Adding Two numbers */
int a;
int b;
int c;
// Assigning integer value to variables A and B
a = 100;
b = 200;
// Adding A value and B value and assign the resultant value to the variable C
c = a + b
// Show the resultant value in the Log
log.info(“Result :” + c);
In the above script, A, B and C are the variables which are used to store or transfer the values.
(Click on the image for an enlarged view)
Note: Variables in the Groovy script are case sensitive. Exercise caution when using them.
The following are the operators supported in Groovy:
Arithmetic Operators
+ Addition operator / String concatenation
– Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
// Arithmetic Operators Samples
// Addition Operator
int x1 = 100 + 200
log.info (“Addition Result :” + x1);
// Concatenation of Two Strings using PLUS ( + ) operator
String city =”Timothy E.” + ” Shepherd”;
log.info(“String Concatenation:” + city);
// Subtraction Operator
int x2 = 200 – 100
log.info (“Subtraction :” + x2);
// Multiplication Operator
int x3 = 10 * 200
log.info (“Multiplication :” + x3);
// Division Operator
int x4 = 200 / 10
log.info (“Division :” + x4);
// Modulus Operator
int x5 = 10 % 3
log.info (“Reminder or Modulus:” + x5);
The following is a screenshot of all of the above scripts and the respective results:
Unary Operators
Unary operators are the ones that work with only one operand. For example: ++ – it is called as Increment operator which increments the current value by 1
Here’s an example
int A = 100;
A++; // Equivalent to A = A + 1
log.info (A);
The above script will produce the output as 101. This increment operation is called post increment. Similarly, we can use this operator as a pre-increment operation as shown below:
int A = 100;
log.info (++A);
There is also (–) the decrement operator. It will decrease the current value by 1. We can implement this operator to the above discussed examples.
int A = 100;
A–; // Equivalent to A = A – 1
log.info (A);
The above script will produce the following output:
Mon Jul 21 18:02:16 IST 2014:INFO:99
Pre and post operations can be used with the decrement operator as well.
Assignment Operators
The basic assignment operator is an equal sign (=). Likewise, there are other useful assignment operators available. They are +=, -=, *=, /=, %=.
Let us see the samples.
int A=100;
A += 10; // Similar to A = A + 10
log.info(A);
The above script produces 110. If we use minus equal to the operator in the below script, output will be 40.
int B=50;
B -= 10;
log.info(B);
Likewise, we can use the remaining operators like this.
int C=10;
C *= 10;
log.info(C);
And,
int D=50;
D /= 10;
log.info(D);
Here’s a reminder operator is used as
int E=10;
E %= 3;
log.info(E);
This will divide the value 10 by 3 and the remainder will be assigned to the variable “E”.
Conclusion
This is just a start and there are many other operators available and supported by groovy such as logic, comparison, conditional etc. which will be discussed in the upcoming tutorials. In the next SoapUI tutorial, we will also learn how to deal with properties in SoapUI Groovy scripts.
Do let us know how you found this tutorial. Please post your feedback and questions in the comments section below. We would love to hear from you.
Hai All..
I am a Beginner in Soap UI
I Want to Know information about groovy script for JSon model
Here example are for XML model
how to write groovy script for Request and Resonse in Json Model
Pls any one help Me fix this…….
Hi,
Can anyone help me in groovy script how shall read a data(token) line by line displayed in a browser.
Hi
I needed help with a task…I have 8 restful service calls .I need to test them in a sequence.
I need to pass the output of preceding restful service as input to the next service.
I have to use SOAP UI and maybe Groovy Scripting / Java
Pls let me know if you can help me.Pls let me know if you need more details.
Hi, How to add assertions by using groovy
Executing this groovy script throws error like
”
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Script11.groovy: 14: Invalid variable name. Must start with a letter but was: ” . At [14:20] @ line 14, column 20. log.info (“Result :” + c); ^ org.codehaus.groovy.syntax.SyntaxException: Invalid variable name. Must start with a letter but was: ” . At [14:20] @ line 14, column 20. at org.codehaus.groovy.control.CompilationUnit$15.call(CompilationUnit.java:760) at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1036) at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:572) at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:550) at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:527) at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:279) at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:258) at groovy.lang.GroovyShell.parseClass(GroovyShell.java:613) at groovy.lang.GroovyShell.parse(GroovyShell.java:625) at groovy.lang.GroovyShell.parse(GroovyShell.java:652) at groovy.lang.GroovyShell.parse(GroovyShell.java:643) at com.eviware.soapui.support.scripting.groovy.SoapUIGroovyScriptEngine.compile(SoapUIGroovyScriptEngine.java:152) at com.eviware.soapui.support.scripting.groovy.SoapUIGroovyScriptEngine.run(SoapUIGroovyScriptEngine.java:97) at com.eviware.soapui.impl.wsdl.teststeps.WsdlGroovyScriptTestStep.run(WsdlGroovyScriptTestStep.java:154) at com.eviware.soapui.impl.wsdl.panels.teststeps.GroovyScriptStepDesktopPanel$RunAction$1.run(GroovyScriptStepDesktopPanel.java:277) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) 1 error”
pls help me… what to do here..
/* Adding Two numbers */
int a;
int b;
int c;
// Assigning integer value to the variables A and B
a = 100;
b = 200;
// Adding A value and B value and assign the resultant value to the variable C
c = a + b
// Show the resultant value in the Log
log.info(“Result :” + c);
I have a JDBC step defined in my soapui script , i want to extract a value like this value from the query response , and assign it to a project variable , is that possible from groovy scripting ?
I want to extract data from excel file that is saved anywhere in directory using groovy script, Can anyone help me?
@Amit Pratap,
To read data from Excel sheet from Groovy, you need to use either JXL.jar or POI.jar file and this file should be kept in SoapUI installation path \ext folder.
And write script using java code.
@Praveen: in your case you need to put the string ‘Result’ in single quote and not in double quote.
tested code-
log.info ‘soapUI script’
int a;
int b;
int c;
a=100;
b=200;
c=a+b;
log.info(‘Result: ‘+c);
I am job less please can you help me
How Can I read value from a property in xml request
e.g.
if i want to read the value of id and send response based on it in mock service, how can i do that
Peraveen Kumar u missed a “;’
c=a+b;
The groovy script errors are due to formatting issues in the example scripts. Re-enter the script quote (“) characters manually. Some of the hyphens (-) need to be re-entered manually as well.
pls help me guys
step 1. generate random number in groovy script step 2. connect to database step 3. verify whether generated random number exist in database or not(check in all rows) if random number exist stop execution else continue execution
// Modulus Operator
int x5 = 10 % 3
log.info (“Reminder or Modulus:” + x5);
It is Remainder, not Reminder.
Is possible with Groovy create de Header Security in one Request?
@sonya,
It’s possible to get the value from JDBC response and assign it to a project variable. Refer the following script.
query = “SELECT FROM < WHERE ID = 103231”
testRunner.testCase.testSuite.project.setPropertyValue(“JDBC_QUERY”,query)
log.info(query)
tc = projectName.testSuites[‘TestSuite’].testCases[‘MyTestcase’]
tstp = tc.getTestStepByName(‘TestStep’)
runner = tstp.run(testRunner,context)
responseHolder = runner.getResponseContent()
runner = null
resultXml = new XmlSlurper().parseText( responseHolder )
relObjIds = resultXml?.ResultSet?.Row?.collect{it.<>}
relObjectId = relObjIds[0]
testRunner.testCase.testSuite.project.setPropertyValue(“ID”,relObjectId.toString())
eg..
id=”some value”, its not allowing me to add tags so consider it as an attribute in the tag inside the request
Good basic start with groovy
Looking forward to up coming tutorial on Groovy Scripting
Adding my comment..
query = “select column_name from table_name where id = 103231
relObjIds = resultXml?.ResultSet?.Row?.collect{it.column_name}
Thanks you so much for sharing this tutorial.
Thanks for making things so easy to understand,
Groovy is looking quite similar to other languages only instead of print/printf/System.println
here we have log.info();
After pasting the script add double inverted commas again, log.info(“Result :” + c);
Problem solved
Good tutorial, thanks