【问题标题】:Spring Cloud Contract - Transforming response in Groovy DSLSpring Cloud Contract - 在 Groovy DSL 中转换响应
【发布时间】:2019-10-25 12:09:58
【问题描述】:

这是我在 groovy 文件中的春季合同:

package com.stubs.contracts

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

[
        Contract.make {
            description "Stub for my endpoint"
            request {
                method POST()
                url("/rest/v1/value/validate") {
                }
                headers {
                    contentType applicationJson()
                }
                body(
                        file("Request_validate_200.json")
                )
            }
            response {
                body(
                        file("Response_validate_200.json")
                )
                headers {
                    contentType applicationJson()
                }
                status OK()
            }
        }
]

我的问题是: 如何覆盖响应正文的值?

我想: 1) 使用请求 JSON 加载文件 2) 从此请求中获取“id”属性值 3) 替换加载的 JSON 响应中的“id”值属性

有可能吗?

【问题讨论】:

    标签: rest groovy spring-cloud wiremock contract


    【解决方案1】:

    你不能开箱即用。你可以像我们在幕后一样使用类加载器 (https://github.com/spring-cloud/spring-cloud-contract/blob/master/specs/spring-cloud-contract-spec-java/src/main/java/org/springframework/cloud/contract/spec/internal/Common.java#L243-L255)。换句话说,你可以像这样创建一个闭包:

    Closure fileLocation = { String relativePath -> 
            URL resource = Thread.currentThread().getContextClassLoader()
                    .getResource(relativePath);
            if (resource == null) {
                throw new IllegalStateException("File [" + relativePath + "] is not present");
            }
            try {
                return new File(resource.toURI());
            }
            catch (URISyntaxException ex) {
                throw new IllegalStateException(ex);
            }
        }
    }
    

    调用fileLocation("Response_validate_200.json") 以检索File,然后将其转换为String,如fileLocation("Response_validate_200.json").text,然后使用JsonSlurper 解析它new groovy.json.JsonSlurper().parseText(fileLocation("Response_validate_200.json").text)。从那以后,您必须使用 slurper 来修改内容,仅此而已。

    【讨论】:

      猜你喜欢
      • 2017-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-27
      • 2017-09-29
      • 2020-10-24
      • 1970-01-01
      相关资源
      最近更新 更多