SpringCloud 对REST的XML支持
2023-12-13 11:54 更新
对于REST合同,我们还支持XML请求和响应主体。XML主体必须作为String
或GString
在body
元素内传递。还可以为请求和响应提供身体匹配器。代替jsonPath(…)
方法,应使用org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath
方法,并以所需的xPath
作为第一个参数,并以适当的MatchingType
作为第二个参数。支持byType()
以外的所有主体匹配器。
这是带有XML响应主体的Groovy DSL合同的示例:
Contract.make { request { method GET() urlPath '/get' headers { contentType(applicationXml()) } } response { status(OK()) headers { contentType(applicationXml()) } body """ <test> <duck type='xtype'>123</duck> <alpha>abc</alpha> <list> <elem>abc</elem> <elem>def</elem> <elem>ghi</elem> </list> <number>123</number> <aBoolean>true</aBoolean> <date>2017-01-01</date> <dateTime>2017-01-01T01:23:45</dateTime> <time>01:02:34</time> <valueWithoutAMatcher>foo</valueWithoutAMatcher> <key><complex>foo</complex></key> </test>""" bodyMatchers { xPath('/test/duck/text()', byRegex("[0-9]{3}")) xPath('/test/duck/text()', byCommand('test($it)')) xPath('/test/duck/xxx', byNull()) xPath('/test/duck/text()', byEquality()) xPath('/test/alpha/text()', byRegex(onlyAlphaUnicode())) xPath('/test/alpha/text()', byEquality()) xPath('/test/number/text()', byRegex(number())) xPath('/test/date/text()', byDate()) xPath('/test/dateTime/text()', byTimestamp()) xPath('/test/time/text()', byTime()) xPath('/test/*/complex/text()', byEquality()) xPath('/test/duck/@type', byEquality()) } } }
以下是带有XML请求和响应主体的YAML合同的示例:
include::{verifier_core_path}/src/test/resources/yml/contract_rest_xml.yml
这是自动生成的XML响应正文测试的示例:
@Test public void validate_xmlMatches() throws Exception { // given: MockMvcRequestSpecification request = given() .header("Content-Type", "application/xml"); // when: ResponseOptions response = given().spec(request).get("/get"); // then: assertThat(response.statusCode()).isEqualTo(200); // and: DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); Document parsedXml = documentBuilder.parse(new InputSource( new StringReader(response.getBody().asString()))); // and: assertThat(valueFromXPath(parsedXml, "/test/list/elem/text()")).isEqualTo("abc"); assertThat(valueFromXPath(parsedXml,"/test/list/elem[2]/text()")).isEqualTo("def"); assertThat(valueFromXPath(parsedXml, "/test/duck/text()")).matches("[0-9]{3}"); assertThat(nodeFromXPath(parsedXml, "/test/duck/xxx")).isNull(); assertThat(valueFromXPath(parsedXml, "/test/alpha/text()")).matches("[\\p{L}]*"); assertThat(valueFromXPath(parsedXml, "/test/*/complex/text()")).isEqualTo("foo"); assertThat(valueFromXPath(parsedXml, "/test/duck/@type")).isEqualTo("xtype"); }
以上内容是否对您有帮助:
更多建议: