In this article, we will demonstrate how to use Groovy Test Step within SoapUI to load database credentials from disk, and then initialize database connection using Groovy. Finally, a practical example of using this database connection will be illustrated.
To set up a database connection from within Groovy Test Step we are going to do the following steps:
First, we have to prepare our test environment. Since many Test Cases within our project will share the same database connection, it is best to store the database initialization Test Step in a separate Test Case. This Test Case can be used to store initialization code for shared libraries as well.
An example of such a structure is visible in the following picture:
Fig. 1. Structure of the SoapUI project that uses a shared library and database initialization Groovy Test Step
We don’t want hardcoded credentials in our code or in JDBC Request test step. That’s why we are going to load them from disk. A code example to do so can be seen below:
When we are running our tests from within SoapUI GUI environment, we have to supply absolute paths, but when we are running our tests from the command line or from e.g. Jenkins server, then we have to use relative paths.
In order to load the database driver from Groovy Test Step we first have to place the database driver in the correct location. When running this test step from SoapUI GUI than we have to find the installation folder of SoapUI (On my Mac this is: /Applications/Development/SoapUI-5.4.0.app)
and put the driver in: Contents/java/app/bin/ext
. On Windows or Linux machines the path can be a little bit different, but it will still be in the bin/ext
folder.
An example with an updated Oracle JDBC (ojdbc8.jar) driver location can be seen in the following picture:
When we have a driver that we want to use in place, we are now able to load and initialize the driver from Groovy code with this script:
Finally, in order to share the object, we are going to register it as a property of the context object, as can be seen from the whole script seen here:
To actually use the database connection we have first to execute the disabled Groovy Test Step that contains the previously described initialization code, and then we can pass the captured reference to the database connection sql object to another function that is going to use it. Here is an example of how to do it from Groovy Test Step:
With a few tricks, we can very easily write reusable Groovy code inside SoapUI Groovy Test Step where we are going to initialize and then reuse the database connection in the form of a Groovy object. This approach allows us to effectively store database credentials on disk in possibly encrypted form, thus avoiding hardcoding these credentials in specific JDBC Request test steps. This also adds to more flexibility and code reusability within SoapUI.