SpringCloud 對(duì)REST的XML支持

2023-12-13 11:54 更新

對(duì)于REST合同,我們還支持XML請(qǐng)求和響應(yīng)主體。XML主體必須作為StringGStringbody元素內(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");
	}


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)