SpringCloud 从文件传递值
2023-12-12 18:03 更新
从版本1.2.0
开始,您可以传递文件中的值。假设您在我们的项目中拥有以下资源。
└── src
└── test
└── resources
└── contracts
├── readFromFile.groovy
├── request.json
└── response.json
进一步假设您的合同如下:
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
进一步假设JSON文件如下:
request.json
{ "status": "REQUEST" }
response.json
{ "status": "RESPONSE" }
当进行测试或存根生成时,文件的内容将传递到请求或响应的主体。文件名必须是相对于合同所在文件夹的位置的文件。
如果您需要以二进制格式传递文件的内容,则足以使用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
每当要使用HTTP和消息传递的二进制有效负载时,都应使用此方法。
以上内容是否对您有帮助:
更多建议: