SoapUI之cookie设置

一、测试背景:

1)接口测试需要完成注册-->登录-->充值,使用soapui构建好测试用例、设置断言后,运行结果如下:

2)recharge接口运行失败,继续查看该接口具体发送的请求及返回结果有无错误:

 3)这里解释下JSESSIONID是干嘛用的。用户登录(login)向服务器发起请求,服务器会创建session会话保存用户的信息,并返回一个JSESSIONID值放到响应头set-cookie中。然后用户继续发起充值(recharge)请求,请求头cookie中会带上同一个JSESSIONID值提交到服务器,从而确定是同一个登录用户发出的请求,服务器就会放行资源,充值成功。

TestCase运行结果中,双击login运行step查看Respouse Message,切换到Raw视图,能看到JSESSIONID相关信息。那我们现在就是要从登录这个响应头中将JSESSSIONID获取到并赋给充值的请求头中。

二、如何实现cookie设置

1)右键Test Step -->Add Step -->Groovy Script,并命名为Setcookie。

 2)在Setcookie中贴入以下代码:

import com.eviware.soapui.support.types.StringToStringMap

def cookiesList = testRunner.testCase.getTestStepByName("login").testRequest.response.responseHeaders["Set-Cookie"]
log.info cookiesList
 
//Get the cookie 
String cookieNew = cookiesList.get(0)
log.info "cookie : "+cookieNew

//Put cookie to a StringMap 
def cookieMap = new StringToStringMap()
cookieMap.put("Cookie",cookieNew)

//Pass cookie to testStep "recharge" of testSuite 
//testRunner.testCase.getTestStepByName("recharge").testRequest.setRequestHeaders(cookieMap);

//Pass cookie to all testSteps of the project 
def time_num= context.expand ('${#TestCase#cookieMap}') 

def testSuiteList =  testRunner.testCase.testSuite.project.getTestSuiteList()
def testCaseList
def testStepList
for(testSuite in testSuiteList){
    testCaseList =  testSuite.getTestCaseList()
    for(testCase in testCaseList){
        testStepList = testCase.getTestStepsOfType(com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep.class)
        for (testStep in testStepList){
             testStep.testRequest.setRequestHeaders(cookieMap)
        }
    }
}

3)重新运行TestCase,运行成功。查看recharge(充值)请求详细信息,显示充值成功。

猜你喜欢

转载自www.cnblogs.com/tudou-22/p/10695238.html