user3174886
user3174886

Reputation: 301

Checking Response header in groovy

I'm trying to test the response header contain X-Duration-MS text. I'm pretty sure The way I'm checking assert is missing main check if the X-Duration-MS is not on the header. Can you please help me to test it right way?

This is my code:

    def httpResponseHeaders = context.testCase.testSteps["Testname"].testRequest.response.responseHeaders
    //log.info (httpResponseHeaders)
    httpResponseHeaders.each
    {
      k,v ->
        if(k=~"X-Duration-MS"){
          assert k == "X-Duration-MS"
      }
    }

Upvotes: 0

Views: 8021

Answers (1)

albciff
albciff

Reputation: 18517

Using groovy Script

You are checking that there is one X-Duration-MS response header despite its value. Then you can use keySet() function on httpResponseHeaders to get all the http header names, and then use contains() to check that your desired header is in the list. So you can try with:

def httpResponseHeaders = context.testCase.testSteps["Testname"].testRequest.response.responseHeaders
assert httpResponseHeaders.keySet().contains("X-Duration-MS")

Using Script Assertion

You can also achieve your goal using Script assertion in your request instead of a Groovy testStep. In your request UI in the down left corner there is an Assertion(0) text, click on it and then use the + button in the Assertion panel to add an Script Assertion. Then inside this script you can do the same are you doing in the Groovy testStep without the need to find the testStep to get the response because in the Script Assertion there is the messageExchange object in the context which you can use to get the details for the current request, response, http headers... So there you can simply use:

def httpResponseHeaders = messageExchange.getResponseHeaders() 
assert httpResponseHeaders.keySet().contains("X-Duration-MS")

enter image description here

Upvotes: 4

Related Questions