How to Write Basic Groovy Script in SoapUI – SoapUi Tutorial #6

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated October 15, 2024

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.

How To Write Groovy Script in SoapUI

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:

Working with Operators 1

Step #2. Enter the name of the step in the dialogue that comes up below and Click OK

Working with Operators 2

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)

Working with operators 66

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.

Working with operators 44

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)

Working with operators 55

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:

Working with Operators 6

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. 

Was this helpful?

Thanks for your feedback!

Recommended Reading

  • Properties in SoapUI

    In this tutorial, you will see how to use properties in SoapUI Groovy Script. Let's get started.  Properties are the central repository to store our information temporarily. They can contain login information like username and password, session data like session id, page context, header information and so on. This is…

  • SoapUI Groovy Scripting concepts

    In this tutorial, we will learn in detail about advanced SoapUI Groovy Scripting Concepts. Let's get started. The previous SoapUI tutorials have been an introduction to SoapUI and its programming concepts. We will now move into more advanced Groovy scripting concepts. Let us do this with Conditional flow statements -…

  • Exception handling in Groovy script

    In this SoapUI tutorial, we will look at how to handle exception in SoapUI Groovy scripts. Let's get started.  Handling runtime exceptions in groovy is similar to Java as the Java libraries are integrated. However, we will discuss the basic concepts in SoapUI and go into the details of exception…

  • Use Methods in SoapUI

    In this tutorial, we will learn how to use methods in SoapUI for bulk test execution. Let's get started. In the last SoapUI tutorial, we learned about conditional statements in Groovy scripts. This tutorial is all about object-oriented programming in SoapUI Groovy scripts, a very interesting and important programming concept.…

  • working with soapui properties

    This tutorial is all about working with SoapUI properties. Let's get started. In the last SoapUI tutorial we saw how to add properties in Groovy script. The property in SoapUI is similar to a variable/ parameter and in this tutorial, we will talk about how to use one in a…

  • soapui tutorials

    In this article, we have compiled a list of Soap UI Tutorials for the benefit of our readers. Let's get started. STH is coming up with another testing tool tutorial. You know how detailed and useful these tutorials are. The tools are SoapUI and SoapUI Pro. We suggest that our…

  • 4 Important Features of SoapUI Pro for Pro Audience – SoapUI Tutorial #12

    In this article, we will look at the 4 important features of SoapUI Pro for Pro Audience. Let's get started. SoapUI comes in two versions - Open Source Free (SoapUI) and SoapUI Pro (now SoapUI NG pro). So far we were discussing common automation concepts and functional testing basics such…

  • soapui tutorial 15

    This tutorial is a Quick SoapUI Guide to store request and response data in a file. We will learn how to store the responses in a file for future reference.  This is the last tutorial in our SoapUI free training series. Click on this link for all the previous tutorials…


24 thoughts on “How to Write Basic Groovy Script in SoapUI – SoapUi Tutorial #6”

  1. @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())

    Reply
  2. @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.

    Reply
  3. 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…….

    Reply
  4. 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();

    Reply
  5. 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

    Reply
  6. 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.

    Reply
  7. Adding my comment..

    query = “select column_name from table_name where id = 103231

    relObjIds = resultXml?.ResultSet?.Row?.collect{it.column_name}

    Reply
  8. 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 ?

    Reply
  9. 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);

    Reply
  10. 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.

    Reply
  11. @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);

    Reply
  12. 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

    Reply

Leave a Comment