如何使用Spring Cloud Contract从Groovy中的RESTful服务调用获取/打印JSON响应

时间:2018-12-19 19:16:40

标签: json spring-boot groovy spring-cloud-contract

在实施Spring Cloud Contract以进行微服务的集成测试时,我已经在Groovy中定义了Contract,并通过将值硬编码到.json文件中来比较了预期的JSON响应。一切正常。

但是,如果我想动态验证而不是具有静态JSON响应,我找到了一种方法,但是我需要从REST端点调用的响应中将动态JSON响应转换为字符串变量。

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

Contract.make {

    request {
        method 'GET'
        url '/micro-service/90640454'
        headers {
            header 'Content-Type': 'application/json;charset=UTF-8'
        }
    }

    response {
        status 200
        headers {
            header 'Content-Type': 'application/json;charset=UTF-8'
        }
        -- how can i get the actual_response here
        body (file('expected_response.json'))
    }
}

1 个答案:

答案 0 :(得分:0)

在身体的响应侧提供execute方法

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

Contract.make {

    request {
        method 'GET'
        url '/micro-service/90640454'
        headers {
            header 'Content-Type': 'application/json;charset=UTF-8'
        }
    }

    response {
        status 200
        headers {
            header 'Content-Type': 'application/json;charset=UTF-8'
        }
        -- how can i get the actual_response here
        body ($(consumer(file('expected_response.json')), producer('assertMe($it)'))
    }
}

然后必须在基类中定义assertMe方法并进行断言。像这样:

public void assertMe(Object o) { ... perform assertions ... }

如果您阅读文档(https://cloud.spring.io/spring-cloud-static/Finchley.SR2/single/spring-cloud.html#contract-matchers),将会发现

  

从JSON读取的对象的类型可以是以下之一,具体取决于JSON路径:

     

字符串:如果指向字符串值。   JSONArray:如果指向列表。   地图:如果您指向地图。   数字:如果您指向整数,双精度号或其他类型的数字。   布尔值:如果您指向布尔值。