W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
對(duì)于REST合同,我們還支持XML請(qǐng)求和響應(yīng)主體。XML主體必須作為String
或GString
在body
元素內(nèi)傳遞。還可以為請(qǐng)求和響應(yīng)提供身體匹配器。代替jsonPath(…?)
方法,應(yīng)使用org.springframework.cloud.contract.spec.internal.BodyMatchers.xPath
方法,并以所需的xPath
作為第一個(gè)參數(shù),并以適當(dāng)?shù)?code class="literal" i="4323">MatchingType作為第二個(gè)參數(shù)。支持byType()
以外的所有主體匹配器。
這是帶有XML響應(yīng)主體的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請(qǐng)求和響應(yīng)主體的YAML合同的示例:
include::{verifier_core_path}/src/test/resources/yml/contract_rest_xml.yml
這是自動(dòng)生成的XML響應(yīng)正文測(cè)試的示例:
@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"); }
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: