codecamp

SpringCloud 要求

HTTP协议只需要在请求中指定方法和URL合同的请求定义中必须包含相同的信息。

Groovy DSL。 

org.springframework.cloud.contract.spec.Contract.make {
	request {
		// HTTP request method (GET/POST/PUT/DELETE).
		method 'GET'

		// Path component of request URL is specified as follows.
		urlPath('/users')
	}

	response {
		//...
		status 200
	}
}

YAML。 

method: PUT
url: /foo

可以指定一个绝对值而不是相对值url,但是建议使用urlPath,因为这样做会使测试独立主机

Groovy DSL。 

org.springframework.cloud.contract.spec.Contract.make {
	request {
		method 'GET'

		// Specifying `url` and `urlPath` in one contract is illegal.
		url('http://localhost:8888/users')
	}

	response {
		//...
		status 200
	}
}

YAML。 

request:
  method: PUT
  urlPath: /foo

request可能包含查询参数

Groovy DSL。 

org.springframework.cloud.contract.spec.Contract.make {
	request {
		//...
		method GET()

		urlPath('/users') {

			// Each parameter is specified in form
			// `'paramName' : paramValue` where parameter value
			// may be a simple literal or one of matcher functions,
			// all of which are used in this example.
			queryParameters {

				// If a simple literal is used as value
				// default matcher function is used (equalTo)
				parameter 'limit': 100

				// `equalTo` function simply compares passed value
				// using identity operator (==).
				parameter 'filter': equalTo("email")

				// `containing` function matches strings
				// that contains passed substring.
				parameter 'gender': value(consumer(containing("[mf]")), producer('mf'))

				// `matching` function tests parameter
				// against passed regular expression.
				parameter 'offset': value(consumer(matching("[0-9]+")), producer(123))

				// `notMatching` functions tests if parameter
				// does not match passed regular expression.
				parameter 'loginStartsWith': value(consumer(notMatching(".{0,2}")), producer(3))
			}
		}

		//...
	}

	response {
		//...
		status 200
	}
}

YAML。 

request:
...
  queryParameters:
    a: b
    b: c
  headers:
    foo: bar
    fooReq: baz
  cookies:
    foo: bar
    fooReq: baz
  body:
    foo: bar
  matchers:
    body:
      - path: $.foo
        type: by_regex
        value: bar
    headers:
      - key: foo
        regex: bar
response:
  status: 200
  fixedDelayMilliseconds: 1000
  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)
    cookies:
      - key: foo2
        regex: bar
      - key: foo3
        predefined:

request可能包含其他请求标头,如以下示例所示:

Groovy DSL。 

org.springframework.cloud.contract.spec.Contract.make {
	request {
		//...
		method GET()
		url "/foo"

		// Each header is added in form `'Header-Name' : 'Header-Value'`.
		// there are also some helper methods
		headers {
			header 'key': 'value'
			contentType(applicationJson())
		}

		//...
	}

	response {
		//...
		status 200
	}
}

YAML。 

request:
...
headers:
  foo: bar
  fooReq: baz

request可能包含其他请求cookie,如以下示例所示:

Groovy DSL。 

org.springframework.cloud.contract.spec.Contract.make {
	request {
		//...
		method GET()
		url "/foo"

		// Each Cookies is added in form `'Cookie-Key' : 'Cookie-Value'`.
		// there are also some helper methods
		cookies {
			cookie 'key': 'value'
			cookie('another_key', 'another_value')
		}

		//...
	}

	response {
		//...
		status 200
	}
}

YAML。 

request:
...
cookies:
  foo: bar
  fooReq: baz

request可能包含一个请求正文

Groovy DSL。 

org.springframework.cloud.contract.spec.Contract.make {
	request {
		//...
		method GET()
		url "/foo"

		// Currently only JSON format of request body is supported.
		// Format will be determined from a header or body's content.
		body '''{ "login" : "john", "name": "John The Contract" }'''
	}

	response {
		//...
		status 200
	}
}

YAML。 

request:
...
body:
  foo: bar

request可能包含多部分元素。要包含多部分元素,请使用multipart方法/部分,如以下示例所示

Groovy DSL。 

YAML。 

request:
  method: PUT
  url: /multipart
  headers:
    Content-Type: multipart/form-data;boundary=AaB03x
  multipart:
    params:
      # key (parameter name), value (parameter value) pair
      formParameter: '"formParameterValue"'
      someBooleanParameter: true
    named:
      - paramName: file
        fileName: filename.csv
        fileContent: file content
  matchers:
    multipart:
      params:
        - key: formParameter
          regex: ".+"
        - key: someBooleanParameter
          predefined: any_boolean
      named:
        - paramName: file
          fileName:
            predefined: non_empty
          fileContent:
            predefined: non_empty
response:
  status: 200

在前面的示例中,我们以两种方式之一定义参数:

Groovy DSL

  • 直接使用映射符号,其中值可以是动态属性(例如formParameter: $(consumer(…​), producer(…​)))。
  • 通过使用允许您设置命名参数的named(…​)方法。命名参数可以设置namecontent您可以通过带有两个参数的方法(例如,named("fileName", "fileContent"))或通过映射表示法(例如,named(name: "fileName", content: "fileContent"))来调用它。

YAML

  • 通过multipart.params部分设置多部分参数
  • 可以通过multipart.named部分设置命名参数(给定参数名称的fileNamefileContent)。该部分包含paramName(参数名称),fileName(文件名称),fileContent(文件内容)字段
  • 可以通过matchers.multipart部分设置动态位

    • 对于参数,请使用params部分,该部分可以接受regexpredefined正则表达式
    • 对于命名参数,请使用named部分,其中首先通过paramName定义参数名称,然后可以通过regex或{12 /传递fileNamefileContent的参数化} 正则表达式

根据该合同,生成的测试如下:

// given:
 MockMvcRequestSpecification request = given()
   .header("Content-Type", "multipart/form-data;boundary=AaB03x")
   .param("formParameter", "\"formParameterValue\"")
   .param("someBooleanParameter", "true")
   .multiPart("file", "filename.csv", "file content".getBytes());

// when:
 ResponseOptions response = given().spec(request)
   .put("/multipart");

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

WireMock存根如下:

			'''
{
  "request" : {
	"url" : "/multipart",
	"method" : "PUT",
	"headers" : {
	  "Content-Type" : {
		"matches" : "multipart/form-data;boundary=AaB03x.*"
	  }
	},
	"bodyPatterns" : [ {
		"matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"formParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n\\".+\\"\\r\\n--\\\\1.*"
  		}, {
    			"matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"someBooleanParameter\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n(true|false)\\r\\n--\\\\1.*"
  		}, {
	  "matches" : ".*--(.*)\\r\\nContent-Disposition: form-data; name=\\"file\\"; filename=\\"[\\\\S\\\\s]+\\"\\r\\n(Content-Type: .*\\r\\n)?(Content-Transfer-Encoding: .*\\r\\n)?(Content-Length: \\\\d+\\r\\n)?\\r\\n[\\\\S\\\\s]+\\r\\n--\\\\1.*"
	} ]
  },
  "response" : {
	"status" : 200,
	"transformers" : [ "response-template", "foo-transformer" ]
  }
}
	'''
SpringCloud HTTP顶级元素
SpringCloud 回应
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

三、Spring Cloud Netflix

SpringCloud Hystrix超时和Ribbon客户

SpringCloud 重试失败的请求

五、Spring Cloud Stream

六、SpringCloud Binder实现

SpringCloud 重试RabbitMQ Binder

SpringCloud Dead-Letter队列处理

八、Spring Cloud Sleuth

SpringCloud 当前Span

十二、Spring Cloud for Cloud Foundry

十三、Spring Cloud Contract

Spring Cloud Contract验证程序设置

SrpingCloud Gradle项目

十五、Spring Cloud网关

Spring Cloud 配置路由谓词工厂和网关过滤工厂

Spring Cloud TLS / SSL

Spring Cloud网关配置

SpringCloud 故障排除

十八、Spring Cloud GCP

Spring Cloud GCP Spring资源

Spring Cloud Spring JDBC

Spring Cloud Redis的Cloud Memorystore

Spring Cloud 云身份识别代理(IAP)身份验证

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }