SpringCloud 契约消费者(生产者合同法)

2024-01-03 17:01 更新

在您不想执行“消费者合同”方法(为每个消费者定义期望)但您更愿意使用“生产者Contracts”(生产者提供合同并发​​布存根)的情况下,足够使用Spring Cloud Contract和Stub Runner选项。可以在此处找到此类设置的示例

首先,请记住添加Stub Runner和Spring Cloud Contract Pact模块作为测试依赖项。

Maven. 

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<!-- Don't forget to add spring-cloud-contract-pact to the classpath! -->
<dependencies>
    <!-- ... -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-contract-pact</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Gradle. 

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

dependencies {
    //...
    testCompile("org.springframework.cloud:spring-cloud-starter-contract-stub-runner")
    // Don't forget to add spring-cloud-contract-pact to the classpath!
    testCompile("org.springframework.cloud:spring-cloud-contract-pact")
}

接下来,只需将Pact Broker的URL传递到以pact://协议为前缀的repositoryRoot例如pact://http://localhost:8085

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureStubRunner(stubsMode = StubRunnerProperties.StubsMode.REMOTE,
		ids = "com.example:beer-api-producer-pact",
		repositoryRoot = "pact://http://localhost:8085")
public class BeerControllerTest {
    //Inject the port of the running stub
    @StubRunnerPort("beer-api-producer-pact") int producerPort;
    //...
}

通过这样的设置:

  • 契约文件将从契约代理下载
  • Spring Cloud Contract将把Pact文件转换为存根定义
  • 存根服务器将启动并被存入存根

有关Pact支持的更多信息,请转至“使用Pact存根下载器”部分。


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号