常見的頂層元素

以下章節描述了最常見的頂層元素

描述

你可以為你的契約新增一個 description。描述是任意文字。以下程式碼展示了一個示例

Groovy
			org.springframework.cloud.contract.spec.Contract.make {
				description('''
given:
	An input
when:
	Sth happens
then:
	Output
''')
			}
YAML
description: Some description
name: some name
priority: 8
ignored: true
request:
  url: /foo
  queryParameters:
    a: b
    b: c
  method: PUT
  headers:
    foo: bar
    fooReq: baz
  body:
    foo: bar
  matchers:
    body:
      - path: $.foo
        type: by_regex
        value: bar
    headers:
      - key: foo
        regex: bar
response:
  status: 200
  headers:
    foo2: bar
    foo3: foo33
    fooRes: baz
  body:
    foo2: bar
    foo3: baz
    nullValue: null
  matchers:
    body:
      - path: $.foo2
        type: by_regex
        value: bar
      - path: $.foo3
        type: by_command
        value: executeMe($it)
      - path: $.nullValue
        type: by_null
        value: null
    headers:
      - key: foo2
        regex: bar
      - key: foo3
        command: andMeToo($it)
Java
Contract.make(c -> {
	c.description("Some description");
}));
Kotlin
contract {
	description = """
given:
	An input
when:
	Sth happens
then:
	Output
"""
}

名稱

你可以為你的契約提供一個名稱。假設你提供的名稱如下:should register a user。如果你這樣做,自動生成的測試名稱將是 validate_should_register_a_user。此外,WireMock 存根中的存根名稱將是 should_register_a_user.json

你必須確保名稱不包含任何會導致生成的測試無法編譯的字元。另外,請記住,如果你為多個契約提供了相同的名稱,你的自動生成的測試將無法編譯,並且你生成的存根會相互覆蓋。

以下示例展示瞭如何為契約新增名稱

Groovy
org.springframework.cloud.contract.spec.Contract.make {
	name("some_special_name")
}
YAML
name: some name
Java
Contract.make(c -> {
	c.name("some name");
}));
Kotlin
contract {
	name = "some_special_name"
}

忽略契約

如果你想忽略某個契約,你可以在外掛配置中設定忽略的契約值,或者在契約本身上設定 ignored 屬性。以下示例展示瞭如何這樣做

Groovy
org.springframework.cloud.contract.spec.Contract.make {
	ignored()
}
YAML
ignored: true
Java
Contract.make(c -> {
	c.ignored();
}));
Kotlin
contract {
	ignored = true
}

正在進行中的契約

正在進行中的契約不會在生產者端生成測試,但允許生成存根。

謹慎使用此功能,因為它可能導致誤報,因為你在實際實現尚未到位的情況下為消費者生成了可用的存根。

如果你想設定一個正在進行中的契約,以下示例展示瞭如何這樣做

Groovy
org.springframework.cloud.contract.spec.Contract.make {
	inProgress()
}
YAML
inProgress: true
Java
Contract.make(c -> {
	c.inProgress();
}));
Kotlin
contract {
	inProgress = true
}

你可以設定 failOnInProgress Spring Cloud Contract 外掛屬性的值,以確保當你的原始碼中至少存在一個正在進行中的契約時,你的構建會失敗。

從檔案傳遞值

從版本 1.2.0 開始,你可以從檔案傳遞值。假設你的專案中包含以下資源

└── src
    └── test
        └── resources
            └── contracts
                ├── readFromFile.groovy
                ├── request.json
                └── response.json

進一步假設你的契約如下所示

Groovy
/*
 * Copyright 2013-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.springframework.cloud.contract.spec.Contract

Contract.make {
	request {
		method('PUT')
		headers {
			contentType(applicationJson())
		}
		body(file("request.json"))
		url("/1")
	}
	response {
		status OK()
		body(file("response.json"))
		headers {
			contentType(applicationJson())
		}
	}
}
YAML
request:
  method: GET
  url: /foo
  bodyFromFile: request.json
response:
  status: 200
  bodyFromFile: response.json
Java
import java.util.Collection;
import java.util.Collections;
import java.util.function.Supplier;

import org.springframework.cloud.contract.spec.Contract;

class contract_rest_from_file implements Supplier<Collection<Contract>> {

	@Override
	public Collection<Contract> get() {
		return Collections.singletonList(Contract.make(c -> {
			c.request(r -> {
				r.url("/foo");
				r.method(r.GET());
				r.body(r.file("request.json"));
			});
			c.response(r -> {
				r.status(r.OK());
				r.body(r.file("response.json"));
			});
		}));
	}

}
Kotlin
import org.springframework.cloud.contract.spec.ContractDsl.Companion.contract

contract {
	request {
		url = url("/1")
		method = PUT
		headers {
			contentType = APPLICATION_JSON
		}
		body = bodyFromFile("request.json")
	}
	response {
		status = OK
		body = bodyFromFile("response.json")
		headers {
			contentType = APPLICATION_JSON
		}
	}
}

進一步假設 JSON 檔案如下所示

request.json
{
  "status": "REQUEST"
}
response.json
{
  "status": "RESPONSE"
}

當進行測試或存根生成時,request.jsonresponse.json 檔案的內容會傳遞給請求或響應的正文。檔案的名稱需要是相對於契約所在資料夾的某個位置中的檔案。

如果你需要以二進位制形式傳遞檔案內容,可以在編碼 DSL 中使用 fileAsBytes 方法,或者在 YAML 中使用 bodyFromFileAsBytes 欄位。

以下示例展示瞭如何傳遞二進位制檔案的內容

Groovy
import org.springframework.cloud.contract.spec.Contract

Contract.make {
	request {
		url("/1")
		method(PUT())
		headers {
			contentType(applicationOctetStream())
		}
		body(fileAsBytes("request.pdf"))
	}
	response {
		status 200
		body(fileAsBytes("response.pdf"))
		headers {
			contentType(applicationOctetStream())
		}
	}
}
YAML
request:
  url: /1
  method: PUT
  headers:
    Content-Type: application/octet-stream
  bodyFromFileAsBytes: request.pdf
response:
  status: 200
  bodyFromFileAsBytes: response.pdf
  headers:
    Content-Type: application/octet-stream
Java
import java.util.Collection;
import java.util.Collections;
import java.util.function.Supplier;

import org.springframework.cloud.contract.spec.Contract;

class contract_rest_from_pdf implements Supplier<Collection<Contract>> {

	@Override
	public Collection<Contract> get() {
		return Collections.singletonList(Contract.make(c -> {
			c.request(r -> {
				r.url("/1");
				r.method(r.PUT());
				r.body(r.fileAsBytes("request.pdf"));
				r.headers(h -> {
					h.contentType(h.applicationOctetStream());
				});
			});
			c.response(r -> {
				r.status(r.OK());
				r.body(r.fileAsBytes("response.pdf"));
				r.headers(h -> {
					h.contentType(h.applicationOctetStream());
				});
			});
		}));
	}

}
Kotlin
import org.springframework.cloud.contract.spec.ContractDsl.Companion.contract

contract {
	request {
		url = url("/1")
		method = PUT
		headers {
			contentType = APPLICATION_OCTET_STREAM
		}
		body = bodyFromFileAsBytes("contracts/request.pdf")
	}
	response {
		status = OK
		body = bodyFromFileAsBytes("contracts/response.pdf")
		headers {
			contentType = APPLICATION_OCTET_STREAM
		}
	}
}
每當你想處理二進位制負載時,無論是對於 HTTP 還是訊息傳遞,都應該使用此方法。

元資料

你可以為你的契約新增 metadata。透過元資料,你可以將配置傳遞給擴充套件。下面是一個使用 wiremock 鍵的示例。其值是一個對映,鍵是 stubMapping,值是 WireMock 的 StubMapping 物件。Spring Cloud Contract 能夠使用你的自定義程式碼修補生成的存根對映的一部分。你可能想這樣做是為了新增 webhooks、自定義延遲或與第三方 WireMock 擴充套件整合。

java
Contract.make(c -> {
	c.metadata(MetadataUtil.map()
		.entry("wiremock", ContractVerifierUtil.map()
			.entry("stubMapping", "{ \"response\" : { \"fixedDelayMilliseconds\" : 2000 } }")));
}));
kotlin
contract {
	metadata("wiremock" to ("stubmapping" to """
{
  "response" : {
	"fixedDelayMilliseconds": 2000
  }
}"""))
}

在以下章節中,你可以找到支援的元資料條目的示例。

HTTP 契約

Spring Cloud Contract 允許你驗證使用 REST 或 HTTP 作為通訊手段的應用。Spring Cloud Contract 驗證對於與契約 request 部分標準匹配的請求,伺服器提供的響應是否與契約 response 部分保持一致。隨後,契約被用於生成 WireMock 存根,對於任何匹配提供標準的請求,這些存根會提供合適的響應。