SpringCloud 将运行器添加到项目
您可以在类路径上同时使用Spring AMQP和Spring Cloud Contract Stub Runner,并设置属性stubrunner.amqp.enabled=true
。请记住用@AutoConfigureStubRunner
注释测试类。
如果您已经在类路径上具有Stream and Integration,则需要通过设置
stubrunner.stream.enabled=false
和stubrunner.integration.enabled=false
属性来显式禁用它们。
假设您具有以下Maven存储库,其中包含spring-cloud-contract-amqp-test
应用程序的已部署存根。
└── .m2 └── repository └── com └── example └── spring-cloud-contract-amqp-test ├── 0.4.0-SNAPSHOT │ ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT.pom │ ├── spring-cloud-contract-amqp-test-0.4.0-SNAPSHOT-stubs.jar │ └── maven-metadata-local.xml └── maven-metadata-local.xml
进一步假设存根包含以下结构:
├── META-INF │ └── MANIFEST.MF └── contracts └── shouldProduceValidPersonData.groovy
考虑以下合同:
Contract.make { // Human readable description description 'Should produce valid person data' // Label by means of which the output message can be triggered label 'contract-test.person.created.event' // input to the contract input { // the contract will be triggered by a method triggeredBy('createPerson()') } // output message of the contract outputMessage { // destination to which the output message will be sent sentTo 'contract-test.exchange' headers { header('contentType': 'application/json') header('__TypeId__': 'org.springframework.cloud.contract.stubrunner.messaging.amqp.Person') } // the body of the output message body([ id : $(consumer(9), producer(regex("[0-9]+"))), name: "me" ]) } }
现在考虑以下Spring配置:
stubrunner: repositoryRoot: classpath:m2repo/repository/ ids: org.springframework.cloud.contract.verifier.stubs.amqp:spring-cloud-contract-amqp-test:0.4.0-SNAPSHOT:stubs stubs-mode: remote amqp: enabled: true server: port: 0
要使用上述合同触发消息,请使用StubTrigger
界面,如下所示:
stubTrigger.trigger("contract-test.person.created.event")
该消息的目的地为contract-test.exchange
,因此Spring AMQP存根运行器集成查找与该交换有关的绑定。
@Bean public Binding binding() { return BindingBuilder.bind(new Queue("test.queue")) .to(new DirectExchange("contract-test.exchange")).with("#"); }
绑定定义绑定队列test.queue
。结果,以下侦听器定义将与合同消息匹配并调用。
@Bean public SimpleMessageListenerContainer simpleMessageListenerContainer( ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.setQueueNames("test.queue"); container.setMessageListener(listenerAdapter); return container; }
此外,以下带注释的侦听器将匹配并被调用:
@RabbitListener(bindings = @QueueBinding(value = @Queue("test.queue"), exchange = @Exchange(value = "contract-test.exchange", ignoreDeclarationExceptions = "true"))) public void handlePerson(Person person) { this.person = person; }
该消息被直接移交给与匹配的SimpleMessageListenerContainer
相关联的MessageListener
的onMessage
方法。
为了避免Spring AMQP在我们的测试期间尝试连接到正在运行的代理,请配置模拟ConnectionFactory
。
要禁用模拟的ConnectionFactory,请设置以下属性:stubrunner.amqp.mockConnection=false
stubrunner: amqp: mockConnection: false
更多建议: