常見的頂級元素

以下各節介紹最常見的頂級元素

描述

您可以為契約新增 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 stub 中的 stub 名稱為 should_register_a_user.json

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

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

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
}

正在進行的契約

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

請謹慎使用此功能,因為它可能導致誤報,因為您為消費者生成了 stub,但實際上並未實現。

如果您想設定一個正在進行的契約,以下示例顯示瞭如何操作

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-present 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"
}

當進行測試或 stub 生成時,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 能夠使用您的自定義程式碼修補生成的 stub 對映的部分。您可能希望這樣做是為了新增 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 stub,對於任何匹配提供條件的請求,這些 stub 提供適當的響應。

© . This site is unofficial and not affiliated with VMware.