从位置获取 Stub 或契约定义
除了从 Artifactory、Nexus 或 Git 中选择 stub 或契约定义之外,您还可以指向驱动器上或类路径上的某个位置。这在多模块项目中特别有用,其中一个模块希望重用另一个模块的 stub 或契约,而无需实际将这些内容安装到本地 maven 仓库或将这些更改提交到 Git。
为了实现这一点,当在 Stub Runner 或 Spring Cloud Contract 插件中设置了仓库根参数时,您可以使用 stubs://
协议。
在此示例中,producer
项目已成功构建,并在 target/stubs
文件夹下生成了 stub。作为消费者,可以使用 stubs://
协议设置 Stub Runner 从该位置获取 stub。
注解
@AutoConfigureStubRunner(
stubsMode = StubRunnerProperties.StubsMode.REMOTE,
repositoryRoot = "stubs://file://location/to/the/producer/target/stubs/",
ids = "com.example:some-producer")
JUnit 4 Rule
@Rule
public StubRunnerRule rule = new StubRunnerRule()
.downloadStub("com.example:some-producer")
.repoRoot("stubs://file://location/to/the/producer/target/stubs/")
.stubsMode(StubRunnerProperties.StubsMode.REMOTE);
JUnit 5 Extension
@RegisterExtension
public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
.downloadStub("com.example:some-producer")
.repoRoot("stubs://file://location/to/the/producer/target/stubs/")
.stubsMode(StubRunnerProperties.StubsMode.REMOTE);
契约和 stub 可以存储在一个位置,其中每个生产者都有自己专用的文件夹用于契约和 stub 映射。在该文件夹下,每个消费者都可以有自己的设置。为了让 Stub Runner 根据提供的 ID 找到专用文件夹,您可以传递 stubs.find-producer=true
属性或 stubrunner.stubs.find-producer=true
系统属性。以下列表显示了契约和 stub 的排列方式:
└── com.example (1)
├── some-artifact-id (2)
│ └── 0.0.1
│ ├── contracts (3)
│ │ └── shouldReturnStuffForArtifactId.groovy
│ └── mappings (4)
│ └── shouldReturnStuffForArtifactId.json
└── some-other-artifact-id (5)
├── contracts
│ └── shouldReturnStuffForOtherArtifactId.groovy
└── mappings
└── shouldReturnStuffForOtherArtifactId.json
1 | 消费者的 group ID |
2 | artifact ID 为 [some-artifact-id] 的消费者 |
3 | artifact ID 为 [some-artifact-id] 的消费者的契约 |
4 | artifact ID 为 [some-artifact-id] 的消费者的映射 |
5 | artifact ID 为 [some-other-artifact-id] 的消费者 |
注解
@AutoConfigureStubRunner(
stubsMode = StubRunnerProperties.StubsMode.REMOTE,
repositoryRoot = "stubs://file://location/to/the/contracts/directory",
ids = "com.example:some-producer",
properties="stubs.find-producer=true")
JUnit 4 Rule
static Map<String, String> contractProperties() {
Map<String, String> map = new HashMap<>();
map.put("stubs.find-producer", "true");
return map;
}
@Rule
public StubRunnerRule rule = new StubRunnerRule()
.downloadStub("com.example:some-producer")
.repoRoot("stubs://file://location/to/the/contracts/directory")
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
.properties(contractProperties());
JUnit 5 Extension
static Map<String, String> contractProperties() {
Map<String, String> map = new HashMap<>();
map.put("stubs.find-producer", "true");
return map;
}
@RegisterExtension
public StubRunnerExtension stubRunnerExtension = new StubRunnerExtension()
.downloadStub("com.example:some-producer")
.repoRoot("stubs://file://location/to/the/contracts/directory")
.stubsMode(StubRunnerProperties.StubsMode.REMOTE)
.properties(contractProperties());