Forum Discussion

jenbromf's avatar
14 years ago

REST Mock: OnRequest-Script, Import external Groovy Scripts

Hi every1,

since it took me quite a long time to find a solution to that problem as a groovy and soapUI newbie, I just want to share it to the world

I'm trying to build a REST Mock Service. The Tutorial proposes two different ways:
- Mocking with Static Content
- Mocking with a custom OnRequest Script

When you design REST resources you will soon get the following problem:

Example 1: http://myrestexam.ple/resource/123456/
Example 2: http://myrestexam.ple/resource/123456/subresource

Mocking with static content says: Hey let’s create a file for every resource to deliver something. So I got my base path and a folder for the resource and a file with the filename 123456 (without extension)

${projectDir}/docroot/resource/123456

But as soon as I want to create a second file or folder for my subresource, Windows tells me, that it is unable to create a directory that has got the name of my previously generated file

${projectDir}/docroot/resource/123456/subresource where 123456 is the name of a directory and a file is not possible!

So I tried Mocking with a custom OnRequestScript

Well ok .. that is the more advanced solution. I thought: “Hey, let’s create some specific mime validators and of course a response controller, which will create my status codes and deliver my specific mime type and return the response”

But those tasks seem to generate very long code, which will be hard to modify or review in the small editor window. And here I thought:

How do I create external groovy scripts, which I can import to my OnRequestScript area? I could transfer large static parts of my script into several external groovy files.

Solution:
I create my external groovy scripts and place them into my project folder, next to my xml file. (Or I choose to create a subfolder and reference that later)

Then I put in the following source code to my OnRequestScript Tab:


def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def gcl = new GroovyClassLoader()
projectPath = groovyUtils.getProjectPath() + "/"

def testObject = gcl.parseClass(new File(projectPath + "Test.groovy")).newInstance()

log.info(testObject.getTestString())


Test.groovy:

class Test {
String getTestString() {
return "Test"
}
}


Now I can create several controller and validation classes, and just import them.

I hope I can help anybody with this small piece of code.

Cheers,

Jens Br.
No RepliesBe the first to reply