SpringCloud 在服務(wù)器端執(zhí)行自定義方法

2023-12-13 09:47 更新

本部分僅對Groovy DSL有效。請查看 “匹配器節(jié)中的動態(tài)Properties”一節(jié),以獲取類似功能的YAML示例。

您可以定義在測試期間在服務(wù)器端執(zhí)行的方法調(diào)用。可以將這種方法添加到配置中定義為“ baseClassForTests”的類中。以下代碼顯示了測試用例的合同部分的示例:

org.springframework.cloud.contract.spec.Contract.make {
	request {
		method 'PUT'
		url $(consumer(regex('^/api/[0-9]{2}$')), producer('/api/12'))
		headers {
			header 'Content-Type': 'application/json'
		}
		body '''\
			[{
				"text": "Gonna see you at Warsaw"
			}]
		'''
	}
	response {
		body(
				path: $(consumer('/api/12'), producer(regex('^/api/[0-9]{2}$'))),
				correlationId: $(consumer('1223456'), producer(execute('isProperCorrelationId($it)')))
		)
		status OK()
	}
}

以下代碼顯示了測試用例的基類部分:

abstract class BaseMockMvcSpec extends Specification {

	def setup() {
		RestAssuredMockMvc.standaloneSetup(new PairIdController())
	}

	void isProperCorrelationId(Integer correlationId) {
		assert correlationId == 123456
	}

	void isEmpty(String value) {
		assert value == null
	}

}

 您不能同時使用String和execute來執(zhí)行串聯(lián)。例如,呼叫header('Authorization', 'Bearer ' + execute('authToken()')) 會導(dǎo)致不正確的結(jié)果。而是調(diào)用header('Authorization', execute('authToken()'))并確保authToken() 方法返回您需要的所有內(nèi)容。

從JSON讀取的對象的類型可以是以下之一,具體取決于JSON路徑:

  • String:如果您指向JSON中的String值。
  • JSONArray:如果您指向JSON中的List
  • Map:如果您指向JSON中的Map。
  • Number:如果您指向JSON中的Integer,Double等。
  • Boolean:如果您指向JSON中的Boolean

在合同的請求部分,您可以指定body應(yīng)該從方法中獲取。

您必須同時提供消費者和生產(chǎn)方。execute部分適用于整個身體-不適用于部分身體。

以下示例顯示如何從JSON讀取對象:

Contract contractDsl = Contract.make {
	request {
		method 'GET'
		url '/something'
		body(
				$(c('foo'), p(execute('hashCode()')))
		)
	}
	response {
		status OK()
	}
}

前面的示例導(dǎo)致在請求正文中調(diào)用hashCode()方法。它應(yīng)類似于以下代碼:

// given:
 MockMvcRequestSpecification request = given()
   .body(hashCode());

// when:
 ResponseOptions response = given().spec(request)
   .get("/something");

// then:
 assertThat(response.statusCode()).isEqualTo(200);


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號