SpringCloud 從文件傳遞值

2023-12-12 18:03 更新

從版本1.2.0開始,您可以傳遞文件中的值。假設(shè)您在我們的項(xiàng)目中擁有以下資源。

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

進(jìn)一步假設(shè)您的合同如下:

Groovy DSL。 

/*
 * Copyright 2013-2019 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

進(jìn)一步假設(shè)JSON文件如下:

request.json

{
  "status": "REQUEST"
}

response.json

{
  "status": "RESPONSE"
}

當(dāng)進(jìn)行測試或存根生成時(shí),文件的內(nèi)容將傳遞到請求或響應(yīng)的主體。文件名必須是相對于合同所在文件夾的位置的文件。

如果您需要以二進(jìn)制格式傳遞文件的內(nèi)容,則足以使用Groovy DSL中的fileAsBytes方法或YAML中的bodyFromFileAsBytes字段。

Groovy DSL。 

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
每當(dāng)要使用HTTP和消息傳遞的二進(jìn)制有效負(fù)載時(shí),都應(yīng)使用此方法。


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號