新手求助:如何基于WSDL和XSD使用WireMock Mock SOAP Web服务
嘿,刚接触SOAP和WireMock完全不用慌!我来一步步带你从WSDL/XSD入手,搞定SOAP服务的Mock,包你能上手~
从WSDL/XSD出发,用WireMock Mock SOAP服务的完整步骤
第一步:先把WSDL/XSD的结构摸清楚
- 先打开你的WSDL文件,找到你要Mock的具体SOAP操作(就是
<operation>标签里定义的业务方法)。 - 提取这个操作对应的请求SOAP信封结构:可以用SoapUI打开WSDL自动生成示例请求,或者直接从WSDL的
<message>和<types>节点里扒对应的XML结构,确保符合XSD的约束。 - 同时准备好你要返回的响应SOAP信封结构,同样要贴合XSD的字段要求,避免返回不符合规范的内容。
第二步:启动WireMock服务器
WireMock有两种启动方式,选你顺手的就行:
- Java项目集成:先在Maven/Gradle里加依赖
<!-- Maven示例 --> <dependency> <groupId>com.github.tomakehurst</groupId> <artifactId>wiremock-jre8</artifactId> <version>2.35.0</version> <scope>test</scope> </dependency>
然后写几行代码启动:
WireMockServer wireMockServer = new WireMockServer(8080); // 指定要监听的端口 wireMockServer.start(); WireMock.configureFor("localhost", 8080); // 配置WireMock客户端
- 独立Jar包运行:下载WireMock的独立Jar包后,直接用命令行启动
java -jar wiremock-jre8-2.35.0.jar --port 8080
第三步:配置Mock规则(匹配请求+返回响应)
WireMock的核心是“匹配特定请求,返回预设响应”,有两种配置方式:
方式1:代码配置(适合Java项目)
比如你要Mock一个GetUserInfo的SOAP操作,代码可以这么写:
// 匹配POST请求到指定路径,且请求体里包含GetUserInfoRequest节点 stubFor(post(urlEqualTo("/your-soap-endpoint")) .withHeader("Content-Type", containing("text/xml")) .withRequestBody(matchingXPath("//soapenv:Body//GetUserInfoRequest")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBodyFile("get-user-info-response.xml")));
这里的get-user-info-response.xml是你提前写好的符合规范的SOAP响应文件,要放在src/test/resources/__files目录下。
方式2:配置文件(独立运行时)
在WireMock的mappings目录下新建一个JSON映射文件,比如get-user-info-mapping.json:
{ "request": { "method": "POST", "url": "/your-soap-endpoint", "headers": { "Content-Type": { "contains": "text/xml" } }, "bodyPatterns": [ { "matchesXPath": "//soapenv:Body//GetUserInfoRequest", "xPathNamespaces": { "soapenv": "http://schemas.xmlsoap.org/soap/envelope/" } } ] }, "response": { "status": 200, "headers": { "Content-Type": "text/xml" }, "bodyFileName": "get-user-info-response.xml" } }
然后把写好的响应XML文件get-user-info-response.xml放在__files目录里,示例内容大概是这样:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:user="http://your-namespace.com/user"> <soapenv:Header/> <soapenv:Body> <user:GetUserInfoResponse> <user:UserId>123</user:UserId> <user:UserName>John Doe</user:UserName> </user:GetUserInfoResponse> </soapenv:Body> </soapenv:Envelope>
第四步:测试你的Mock服务
用Postman或者SoapUI发送符合规则的SOAP请求到http://localhost:8080/your-soap-endpoint,就能收到你预设的响应啦!
几个实用小Tips
- 复杂XML结构别手动写,用SoapUI生成示例后改,能省很多踩坑时间。
- XPath匹配一定要加命名空间声明,不然会匹配失败,这点很容易忘!
- 如果需要根据请求参数返回动态响应,可以开启WireMock的响应模板功能:代码里加
wireMockServer.enableResponseTemplates(),或者启动Jar时加--global-response-templates,然后在响应里用模板语法动态生成内容。
内容的提问来源于stack exchange,提问作者Vinay
相关产品推荐
相关产品推荐

