Spring Cloud Contract 和两个既是生产者又是消费者的服务

Spring Cloud Contract and two services that are both producers and consumers

TL;DR:如何为交换信息的两个服务生成存根(因此两者都是生产者和消费者)?

嗨,

我正在开发一个使用微服务架构的应用程序,其中包括 Maven、Spring Boot、Spring Cloud Stream,以及用于集成测试的 Spring Cloud Contract Verifier 和 Stub Runner。我正在使用事件源通过 Kafka 发布事件。所以我有这样的东西:

my-app
|-- pom.xml (sets up both subprojects as children)
|-- person-service (handles person's money)
|  |-- src/main/java/person/EventProducer.java (produces a personCreated event)
|  `-- src/main/java/person/EventConsumer.java (consumes an objectBought event)
`-- object-service (handles objects that can be bought)
   |-- src/main/java/object/EventProducer.java (produces an objectBought event)
   `-- src/main/java/object/EventConsumer.java (consumes a personCreated event)

现在,我的问题是,对于事件溯源,两种服务都是生产者和消费者。所以我有两个服务生成存根供另一个服务使用,如下所示:

个人服务集成测试

@SpringBootTest(classes = PersonApplication.class, webEnvironment = RANDOM_PORT)
@AutoConfigureStubRunner(ids = "example.com:object-service", stubsMode = LOCAL)
class PersonIntegrationTests extends Specification {
    @Inject StubTrigger stubTrigger
    // tests
}

对象服务集成测试

@SpringBootTest(classes = ObjectApplication.class, webEnvironment = RANDOM_PORT)
@AutoConfigureStubRunner(ids = "com.example:person-service", stubsMode = LOCAL)
class ObjectIntegrationTests extends Specification {
    @Inject StubTrigger stubTrigger
    // tests
}

现在,当然,父项目中的 运行ning mvn clean install 给我一个错误,因为无论构建顺序如何,另一个项目中的存根尚未生成。

我查看了 Spring Cloud Contract Verifier 文档及其示例,但我还没有找到针对这种情况的解决方案。

现在,作为解决方法,我先 运行 首先 mvn clean install -DskipTests 生成存根,然后 mvn clean install 到 运行 所有测试。我还尝试过设置两个服务都可以使用的外部合同项目,但每个服务仍然会生成自己的存根。我认为将 stubsMode 更改为 CLASSPATH 也无济于事,因为仍然需要首先创建存根...

我想创建一个 "stub service" 来实现每个服务的生产者,这样每个项目都会引用它来获取存根(所以我会在每个集成测试中使用 ids = "com.example:stub-service" ).但这似乎很麻烦,并且可能导致人为错误,因为合同中的每个更改和 Event Store 中发布的每个附加服务都需要反映在存根服务中。

我的问题是:在 运行 集成测试之前,是否有更好的方法为两个项目生成存根?我希望能够仅使用 mvn clean install 构建和 运行 集成测试。

这是个很好的问题。这是一个先有鸡还是先有蛋的问题。

Right now as a workaround I run first mvn clean install -DskipTests to generate the stubs first, then mvn clean install to run all tests. I've also tried setting up an external contracts project that both services could use, but each service still generates its own stubs

这似乎很有道理。您还可以将一些测试放在不同的套件中,首先 运行 具有一个配置文件的测试(例如 producer),然后是另一个(例如 consumer)。但是你做的似乎是最快的。

您可以在 Spring Cloud Contract 中提出问题,我们可以尝试研究在这种情况下如何让开发人员的生活更轻松。