Soap模拟第三方webservice接口通信

在项目中常需要和第三方接口进行联调通信, 但往往由于各种限制没办法实现即用即取。 所以我们有时候会使用SoapUI模拟请求第三方返回。

安装SoapUI 

Download REST & SOAP Automated API Testing Tool | Open Source | SoapUI

Soapui调用webservice接口

部署完成之后进入SoapUI 首页,点击File->New Soap Project->New REST MockService->Add new mock action, 选择请求方式以及请求Url->New MockResponse

Soap模拟第三方webservice接口通信_第1张图片

双击Response, 可设置返回状态码、返回体格式以及返回内容

Soap模拟第三方webservice接口通信_第2张图片

 

{
    "msg": "success",
    "code": 0,
    "data": {
        "ave temperature": 30.6,
        "max temperature":36.8
    }
}

双击TestMockservice, 点击设置。 填写自己的ip以及指定端口。 修改完成之后点击左边运行按钮

Soap模拟第三方webservice接口通信_第3张图片

 Soap模拟第三方webservice接口通信_第4张图片

 

使用Postman调用接口 , url拼接为http://ip:指定端口/mock action模块设置的Url. 点击发送即可看到设置返回内容。 自此一个简单的第三方请求返回已设置完成

Soap模拟第三方webservice接口通信_第5张图片

 

进阶版

模拟请求超时返回

双击MockResponse, 切换到Script模式之后输入以下内容。 编辑成功之后点击运行

def timeout = 60000
Thread.sleep(timeout)

Soap模拟第三方webservice接口通信_第6张图片

 这个时候调用接口, 接口就会按照指定时间之后再返回数据

Soap模拟第三方webservice接口通信_第7张图片

 

 

get请求根据不同入参返回指定内容

get请求中可使用MockRequest.httpRequest.getParameter方法获取指定入参并进行判断。 还是拿上面接口进行举例说明当station参数等于beijing是最高气温为30,等于hainan时返回38.

先再此基础上新增New MockResponse返回。双击mock action选择SCRIPT

 

Soap模拟第三方webservice接口通信_第8张图片

 

 

// 获取请求Url
def requestPath = mockRequest.getPath()
log.info "Path: "+ requestPath

//获取参数station内容
def station= mockRequest.httpRequest.getParameter('station')
log.info station
//对不同进行制定指定返回内容
if (station == "beijing")
	return "beijingResponse"
else
	return "hainanResponse"

使用Postman调用接口 , url拼接为http://ip:指定端口/mock action模块设置的Url. 点击发送即可看到设置返回内容。

Soap模拟第三方webservice接口通信_第9张图片

 post请求根据不同入参返回指定内容

post请求中可使用MockRequest.requestContent方法获取指定入参并进行判断。 还是拿上面接口进行举例说明当station参数等于beijing是最高气温为30,等于hainan时返回38.

先把接口切换成Post请求方式

Soap模拟第三方webservice接口通信_第10张图片

 双击mock action选择SCRIPT

//post方式获取入参
import groovy.json.JsonSlurper
def station = new JsonSlurper().parseText(mockRequest.requestContent)."station"
if (station == "beijing")
	return "beijingResponse"
else
	return "hainanResponse"

 put请求根据不同入参返回指定内容

由于SoapUI官网遗留问题无法直接获取Put请求如此, 所以这里先使用mockRequest.request.inputStream方法先获取入参再进行转换

//put方式获取入参
import groovy.json.JsonSlurper
def slurper =  new JsonSlurper()
InputStream is = mockRequest.request.inputStream
BufferedReader br = new BufferedReader(new inputStreamReader(is, "UTF-8"))
StringBuilder sb = new StringBuilder()
while((s=br.readLine())!=null){
	sb.append(s)
}
String payLoad = sb.toString()
log.info payLoad
def station = slurper.parseText(payLoad)."station"
if (station == "beijing")
	return "beijingResponse"
else
	return "hainanResponse"

你可能感兴趣的:(软件测试,测试工具)