Nikita Rysin
Nikita Rysin

Reputation: 29

How to use contains with switch in Groovy

Using SoapUI 5.2.1 and Groovy. TestCase has 2 Test Steps:

1) SOAP Request "create"

2) Groovy Script

Goal was to find if exact word is in the response. For example, if response contains word "yes" script should show message.

I achieved it by simple if-else & .contains() After i was thinking about switch and how can i do it this way.

I found old solution here Can switch use String.contains? but it doesn't work for me. I always fall into default

So, I'm stuck. Goal now is to find if exact word is in the response using switch, because in future there will be lot's of different cases.

SOAP "create" has response and we're interested in Body part of this response, because script extracte exactly body.

<env:Body>
 <data ...>
  <transactions>
   <next_step>yes</next>
   <message>that word</message>
  </transactions>
 </data>
</env:Body>

And the Groovy script

response = context.expand('$create#Response#://env:Body}')

switch (response)
{
 case ~/.*word.*/:
  log.info "found"
  break
 case ~/.*damn.*/:
  log.info "found that shouldn't be found"
  break
 default:
  log.info "doesn't work"
}

response.toClass() is java.lang.String

Upvotes: 0

Views: 1863

Answers (2)

KKS
KKS

Reputation: 558

use closure e.g.

response = context.expand('$create#Response#://env:Body}')

switch (response)
{
 case { it.contains('word') }:
  log.info "found"
  break
 case { it.contains('damn') }:
  log.info "found that shouldn't be found"
  break
 default:
  log.info "doesn't work"
}

Upvotes: 0

Rao
Rao

Reputation: 21379

Here is the one of the best approach if you want to check if the expected content is present in the response or not.

With this approach

  • Do not require additional groovy script test step.
  • You can check different string as expected content.

Here are the steps:

  1. For the Soap Request test step, add "Contains" Assertion.
  2. Provide the value as ${#TestCase#EXPECTED_CONTENT} as expected content.
  3. In the test case level, add a custom property, EXPECTED_CONTENT and provide the string value that is expected for current test case. Similarly, you can have different strings as expected value at different tests.

Good part is that you never have to modify the assertion, just change the test case level property value. Isn't simple?

Upvotes: 1

Related Questions