Spring Cloud中的契约测试

本文介绍了如何在Spring Cloud中进行契约测试,包括Provider端的Contract编写、测试基类创建、Artifact发布,以及Consumer端的stub runner配置和测试代码实现,确保服务间API交互的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


这里契约测试基于Spring Cloud Contract来编写,大致流程如下所示:

  • 在Provider使用groovy DSL编写Contract
  • 通过Contract Verifier验证Contract所生成的测试
  • 测试通过后将Artifact(stub.jar)发布到Maven仓库中
  • 在Consumer端pull下相应的Artifact(stub.jar)
  • 运行测试,同时以Artifact作为基础设施启动Stub server
  • 在测试中向Stub server发送请求验证API的正确性

Provider

添加gradle插件和依赖

buildscript {
    ext {
        springBootVersion = '2.0.5.RELEASE'
        springColudContractVersion = '2.0.2.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        // ......
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath("org.springframework.cloud:spring-cloud-contract-gradle-plugin:${springColudContractVersion}")
        // ......
    }
}

// ......
apply plugin: 'groovy'
apply plugin: 'spring-cloud-contract'
// ......


dependencies {
    // ......
    testCompile 'org.springframework.cloud:spring-cloud-starter-contract-verifier'
    // ......
}

编写Contract

按照Spring Cloud Contract的约定,groovy编写的DSL文件需要在在src/test/resources/contracts/目录下。

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

Contract.make {
  request {
    url "/goods"
    method GET()
  }

  response {
    status 200
    headers {
      contentType applicationJson()
    }
    body '''
            [{
                "id"   : 1,
                "name" : "123",
            },
            {
                "id"   : 2,
                "name" : "456",
            },
            {
                "id"   : 3,
                "name" : "789",
            }]
        '''
  }
}

创建测试基类

给从Contract生成的测试类指定一个基类。按照Spring Cloud Contract的约定基类以Base结尾。

@RunWith(SpringRunner.class)
@SpringBootTest
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值