消息

Spring Cloud Contract 允许你验证使用消息传递作为 沟通方式。本文档中展示的所有集成都适用于Spring, 但你也可以自己创建一个并使用它。spring-doc.cadn.net.cn

DSL 消息传递顶层元素

消息传输的DSL看起来和专注于HTTP的有点不同。这 以下章节将解释这些差异:spring-doc.cadn.net.cn

由方法触发的输出

输出消息可以通过调用方法(例如调度合同 开始时间和发送消息时),如下示例所示:spring-doc.cadn.net.cn

槽的
def dsl = Contract.make {
	// Human readable description
	description 'Some description'
	// Label by means of which the output message can be triggered
	label 'some_label'
	// input to the contract
	input {
		// the contract will be triggered by a method
		triggeredBy('bookReturnedTriggered()')
	}
	// output message of the contract
	outputMessage {
		// destination to which the output message will be sent
		sentTo('output')
		// the body of the output message
		body('''{ "bookName" : "foo" }''')
		// the headers of the output message
		headers {
			header('BOOK-NAME', 'foo')
		}
	}
}
YAML
# Human readable description
description: Some description
# Label by means of which the output message can be triggered
label: some_label
input:
  # the contract will be triggered by a method
  triggeredBy: bookReturnedTriggered()
# output message of the contract
outputMessage:
  # destination to which the output message will be sent
  sentTo: output
  # the body of the output message
  body:
    bookName: foo
  # the headers of the output message
  headers:
    BOOK-NAME: foo

在前述示例中,输出消息发送于输出如果一个方法称为书归来触发被召唤。在消息发布者端,我们生成 测试调用该方法来触发消息。在消费者方面,你可以使用some_label触发信息。spring-doc.cadn.net.cn

消费者/生产者

本节仅适用于Groovy DSL。

在HTTP中,你有一个概念客户端/存根和服务器/测试表示法。你也可以 在信息传递中应用这些范式。此外,Spring Cloud 合同验证器也支持。 提供消费者制作人方法 (注意你可以使用其中一种或$提供方法消费者制作人部分)。spring-doc.cadn.net.cn

常见

输入输出消息部门,你可以打电话断言与名称一起 一方法(例如,assertThatMessageIsOnTheQueue()你在 基础类或静态导入。Spring Cloud Contract 运行的是这种方法 在生成的测试中。spring-doc.cadn.net.cn

集成

您可以使用以下集成配置之一:spring-doc.cadn.net.cn

由于我们使用 Spring Boot,如果你在类路径中添加了这些库中的一个,所有 消息配置会自动设置。spring-doc.cadn.net.cn

记得放@AutoConfigureMessageVerifier在你的基类上 生成测试。否则,Spring Cloud Contract 的消息部分就不支持 工作。

如果你想用 Spring Cloud Stream,记得在 上添加测试依赖org.springframework.cloud:spring-cloud-stream如下:spring-doc.cadn.net.cn

梅文
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-stream</artifactId>
    <type>test-jar</type>
    <scope>test</scope>
    <classifier>test-binder</classifier>
</dependency>
格拉德勒
testImplementation(group: 'org.springframework.cloud', name: 'spring-cloud-stream', classifier: 'test-binder')

手动集成测试

测试的主要接口是org.springframework.cloud.contract.verifier.messaging.MessageVerifierSenderorg.springframework.cloud.contract.verifier.messaging.MessageVerifierReceiver. 它定义了如何发送和接收消息。spring-doc.cadn.net.cn

在测试中,你可以注射一个合同验证者消息交换发送和接收 合同后面的消息。然后加上@AutoConfigureMessageVerifier对你的考验。 以下示例展示了如何实现:spring-doc.cadn.net.cn

@RunWith(SpringTestRunner.class)
@SpringBootTest
@AutoConfigureMessageVerifier
public static class MessagingContractTests {

  @Autowired
  private MessageVerifier verifier;
  ...
}
如果你的考试也要求存根,那@AutoConfigureStubRunner包括 消息配置,所以你只需要一个注释。

生产者端消息测试生成

拥有输入输出消息DSL中的部分结果是测试的创建 出版商方面。默认情况下,会创建JUnit 4测试。然而,还有一个 可以创建JUnit 5、TestNG或Spock测试。spring-doc.cadn.net.cn

目的地传给信息已发送至可能有不同的情况 不同消息实现的含义。对于流与整合来说,是 首次解决为目的地频道的。那么,如果不存在这样的目的地, 它被解析为一个频道名称。对于骆驼来说,这是一个特定的组件(例如,JMS).

请考虑以下合同:spring-doc.cadn.net.cn

槽的
def contractDsl = Contract.make {
	name "foo"
	label 'some_label'
	input {
		triggeredBy('bookReturnedTriggered()')
	}
	outputMessage {
		sentTo('activemq:output')
		body('''{ "bookName" : "foo" }''')
		headers {
			header('BOOK-NAME', 'foo')
			messagingContentType(applicationJson())
		}
	}
}
YAML
label: some_label
input:
  triggeredBy: bookReturnedTriggered
outputMessage:
  sentTo: activemq:output
  body:
    bookName: foo
  headers:
    BOOK-NAME: foo
    contentType: application/json

对于上述例子,将创建以下测试:spring-doc.cadn.net.cn

JUnit
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import org.junit.Test;
import org.junit.Rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper;
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage;
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging;

import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat;
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*;
import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson;
import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers;
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes;

public class FooTest {
	@Autowired ContractVerifierMessaging contractVerifierMessaging;
	@Autowired ContractVerifierObjectMapper contractVerifierObjectMapper;

	@Test
	public void validate_foo() throws Exception {
		// when:
			bookReturnedTriggered();

		// then:
			ContractVerifierMessage response = contractVerifierMessaging.receive("activemq:output",
					contract(this, "foo.yml"));
			assertThat(response).isNotNull();

		// and:
			assertThat(response.getHeader("BOOK-NAME")).isNotNull();
			assertThat(response.getHeader("BOOK-NAME").toString()).isEqualTo("foo");
			assertThat(response.getHeader("contentType")).isNotNull();
			assertThat(response.getHeader("contentType").toString()).isEqualTo("application/json");

		// and:
			DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()));
			assertThatJson(parsedJson).field("['bookName']").isEqualTo("foo");
	}

}
斯波克
import com.jayway.jsonpath.DocumentContext
import com.jayway.jsonpath.JsonPath
import spock.lang.Specification
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierObjectMapper
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessage
import org.springframework.cloud.contract.verifier.messaging.internal.ContractVerifierMessaging

import static org.springframework.cloud.contract.verifier.assertion.SpringCloudContractAssertions.assertThat
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.*
import static com.toomuchcoding.jsonassert.JsonAssertion.assertThatJson
import static org.springframework.cloud.contract.verifier.messaging.util.ContractVerifierMessagingUtil.headers
import static org.springframework.cloud.contract.verifier.util.ContractVerifierUtil.fileToBytes

class FooSpec extends Specification {
	@Autowired ContractVerifierMessaging contractVerifierMessaging
	@Autowired ContractVerifierObjectMapper contractVerifierObjectMapper

	def validate_foo() throws Exception {
		when:
			bookReturnedTriggered()

		then:
			ContractVerifierMessage response = contractVerifierMessaging.receive("activemq:output",
					contract(this, "foo.yml"))
			response != null

		and:
			response.getHeader("BOOK-NAME") != null
			response.getHeader("BOOK-NAME").toString() == 'foo'
			response.getHeader("contentType") != null
			response.getHeader("contentType").toString() == 'application/json'

		and:
			DocumentContext parsedJson = JsonPath.parse(contractVerifierObjectMapper.writeValueAsString(response.getPayload()))
			assertThatJson(parsedJson).field("['bookName']").isEqualTo("foo")
	}

}

消费者存根生成

与HTTP部分不同,在消息传递中,我们需要在JAR内部发布合同定义,且 一个残头。然后在消费者端进行解析,创建合适的 stubbed 路由。spring-doc.cadn.net.cn

如果你的类路径上有多个框架,Stub Runner 需要 定义应该使用哪一种。假设你有AMQP、Spring Cloud Stream和Spring Integration。 在类路径上,并且你想用 Spring AMQP。然后你需要设置spring.cloud.contract.stubrunner.stream.enabled=falsespring.cloud.contract.stubrunner.integration.enabled=false. 这样,唯一剩下的框架就是 Spring AMQP。

存根触发

要触发消息,请使用StubTrigger界面,如下示例所示:spring-doc.cadn.net.cn

import java.util.Collection;
import java.util.Map;

/**
 * Contract for triggering stub messages.
 *
 * @author Marcin Grzejszczak
 */
public interface StubTrigger {

	/**
	 * Triggers an event by a given label for a given {@code groupid:artifactid} notation.
	 * You can use only {@code artifactId} too.
	 *
	 * Feature related to messaging.
	 * @param ivyNotation ivy notation of a stub
	 * @param labelName name of the label to trigger
	 * @return true - if managed to run a trigger
	 */
	boolean trigger(String ivyNotation, String labelName);

	/**
	 * Triggers an event by a given label.
	 *
	 * Feature related to messaging.
	 * @param labelName name of the label to trigger
	 * @return true - if managed to run a trigger
	 */
	boolean trigger(String labelName);

	/**
	 * Triggers all possible events.
	 *
	 * Feature related to messaging.
	 * @return true - if managed to run a trigger
	 */
	boolean trigger();

	/**
	 * Feature related to messaging.
	 * @return a mapping of ivy notation of a dependency to all the labels it has.
	 */
	Map<String, Collection<String>> labels();

}

为了方便起见,StubFinder接口扩展StubTrigger,所以你只需要一个或者另一个测试。spring-doc.cadn.net.cn

StubTrigger给你以下触发消息的选项:spring-doc.cadn.net.cn

标签触发

以下示例展示了如何触发带有标签的消息:spring-doc.cadn.net.cn

stubFinder.trigger('return_book_1')

按组和文物ID触发

以下示例展示了如何通过组和文件ID触发消息:spring-doc.cadn.net.cn

stubFinder.trigger('org.springframework.cloud.contract.verifier.stubs:streamService', 'return_book_1')

由工件ID触发

以下示例展示了如何从工件ID触发消息:spring-doc.cadn.net.cn

stubFinder.trigger('streamService', 'return_book_1')

触发所有消息

以下示例展示了如何触发所有消息:spring-doc.cadn.net.cn

stubFinder.trigger()

Apache Camel 的消费者端消息传递

Spring Cloud Contract Stub Runner 的消息模块为你提供了与 Apache Camel 集成的简单方式。对于提供的工件,它会自动下载存根并注册所需信息 路线。spring-doc.cadn.net.cn

将Apache Camel加入项目

你可以在类路径上同时安装Apache Camel和Spring Cloud Contract Stub Runner。记得给测试类做注释:@AutoConfigureStubRunner.spring-doc.cadn.net.cn

禁用该功能

如果你需要禁用这个功能,可以设置spring.cloud.contract.stubrunner.camel.enabled=false财产。spring-doc.cadn.net.cn

例子

假设我们有以下 Maven 仓库,里面部署了存根骆驼服役应用:spring-doc.cadn.net.cn

└── .m2
    └── repository
        └── io
            └── codearte
                └── accurest
                    └── stubs
                        └── camelService
                            ├── 0.0.1-SNAPSHOT
                            │   ├── camelService-0.0.1-SNAPSHOT.pom
                            │   ├── camelService-0.0.1-SNAPSHOT-stubs.jar
                            │   └── maven-metadata-local.xml
                            └── maven-metadata-local.xml

此外,假设存根包含以下结构:spring-doc.cadn.net.cn

├── META-INF
│   └── MANIFEST.MF
└── repository
    ├── accurest
    │   └── bookReturned1.groovy
    └── mappings

现在考虑以下合同:spring-doc.cadn.net.cn

Contract.make {
	label 'return_book_1'
	input {
		triggeredBy('bookReturnedTriggered()')
	}
	outputMessage {
		sentTo('rabbitmq:output?queue=output')
		body('''{ "bookName" : "foo" }''')
		headers {
			header('BOOK-NAME', 'foo')
		}
	}
}

要触发来自return_book_1标签,我们使用StubTrigger界面,具体如下:spring-doc.cadn.net.cn

stubFinder.trigger("return_book_1")

这会向合同输出消息中描述的目的地发送消息。spring-doc.cadn.net.cn

带有 Spring 集成的消费者端消息传递

Spring Cloud 合同存根的消息模块为您提供了一种简单的方式与 Spring 集成。对于提供的工件,它会自动下载存根并注册所需的路由。spring-doc.cadn.net.cn

将跑者加入项目

你可以同时在classpath 上同时放置 Spring Integration 和 Spring Cloud Contract Stub Runner。记得给你的测试类做注释@AutoConfigureStubRunner.spring-doc.cadn.net.cn

禁用该功能

如果你需要禁用这个功能,可以设置spring.cloud.contract.stubrunner.integration.enabled=false财产。spring-doc.cadn.net.cn

例子

假设你有以下 Maven 仓库,并部署了存根整合服务应用:spring-doc.cadn.net.cn

└── .m2
    └── repository
        └── io
            └── codearte
                └── accurest
                    └── stubs
                        └── integrationService
                            ├── 0.0.1-SNAPSHOT
                            │   ├── integrationService-0.0.1-SNAPSHOT.pom
                            │   ├── integrationService-0.0.1-SNAPSHOT-stubs.jar
                            │   └── maven-metadata-local.xml
                            └── maven-metadata-local.xml

进一步假设存根包含以下结构:spring-doc.cadn.net.cn

├── META-INF
│   └── MANIFEST.MF
└── repository
    ├── accurest
    │   └── bookReturned1.groovy
    └── mappings

请考虑以下合同:spring-doc.cadn.net.cn

Contract.make {
	label 'return_book_1'
	input {
		triggeredBy('bookReturnedTriggered()')
	}
	outputMessage {
		sentTo('output')
		body('''{ "bookName" : "foo" }''')
		headers {
			header('BOOK-NAME', 'foo')
		}
	}
}

现在考虑以下春季集成路径:spring-doc.cadn.net.cn

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
			 xmlns:beans="http://www.springframework.org/schema/beans"
			 xmlns="http://www.springframework.org/schema/integration"
			 xsi:schemaLocation="http://www.springframework.org/schema/beans
			https://www.springframework.org/schema/beans/spring-beans.xsd
			http://www.springframework.org/schema/integration
			http://www.springframework.org/schema/integration/spring-integration.xsd">


	<!-- REQUIRED FOR TESTING -->
	<bridge input-channel="output"
			output-channel="outputTest"/>

	<channel id="outputTest">
		<queue/>
	</channel>

</beans:beans>

要触发来自return_book_1标签,使用以下StubTrigger接口,作为 遵循:spring-doc.cadn.net.cn

stubFinder.trigger('return_book_1')

这会向合同输出消息中描述的目的地发送消息。spring-doc.cadn.net.cn

使用 Spring Cloud Stream 进行消费者端消息传递

Spring Cloud 合同存根生成器的消息模块为你提供了一个简单的方式与 Spring Stream 集成。对于提供的工件,它会自动下载存根并注册所需的路由。spring-doc.cadn.net.cn

如果 Stub Runner 与 Stream 的集成信息已发送至字符串 首先确定为目的地是通道,根本不是目的地存在,目的地被解析为频道名称。

如果你想用 Spring Cloud Stream,记得添加依赖org.springframework.cloud:spring-cloud-stream测试支持如下:spring-doc.cadn.net.cn

梅文
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-stream-test-binder</artifactId>
    <scope>test</scope>
</dependency>
格拉德勒
testImplementation('org.springframework.cloud:spring-cloud-stream-test-binder')

将跑者加入项目

你可以同时在classpath 上同时设置 Spring Cloud Stream 和 Spring Cloud 合同存根运行工具。记得为你的测试类注释@AutoConfigureStubRunner.spring-doc.cadn.net.cn

禁用该功能

如果你需要禁用这个功能,可以设置spring.cloud.contract.stubrunner.stream.enabled=false财产。spring-doc.cadn.net.cn

例子

假设你有以下 Maven 仓库,并部署了存根流媒体服务应用:spring-doc.cadn.net.cn

└── .m2
    └── repository
        └── io
            └── codearte
                └── accurest
                    └── stubs
                        └── streamService
                            ├── 0.0.1-SNAPSHOT
                            │   ├── streamService-0.0.1-SNAPSHOT.pom
                            │   ├── streamService-0.0.1-SNAPSHOT-stubs.jar
                            │   └── maven-metadata-local.xml
                            └── maven-metadata-local.xml

进一步假设存根包含以下结构:spring-doc.cadn.net.cn

├── META-INF
│   └── MANIFEST.MF
└── repository
    ├── accurest
    │   └── bookReturned1.groovy
    └── mappings

请考虑以下合同:spring-doc.cadn.net.cn

Contract.make {
	label 'return_book_1'
	input { triggeredBy('bookReturnedTriggered()') }
	outputMessage {
		sentTo('returnBook')
		body('''{ "bookName" : "foo" }''')
		headers { header('BOOK-NAME', 'foo') }
	}
}

现在考虑以下 Spring Cloud Stream 函数配置:spring-doc.cadn.net.cn

@ImportAutoConfiguration(TestChannelBinderConfiguration.class)
@Configuration(proxyBeanMethods = true)
@EnableAutoConfiguration
protected static class Config {

	@Bean
	Function<String, String> test1() {
		return (input) -> {
			println "Test 1 [${input}]"
			return input
		}
	}

}

现在考虑以下Spring配置:spring-doc.cadn.net.cn

spring.cloud.contract.stubrunner.repositoryRoot: classpath:m2repo/repository/
spring.cloud.contract.stubrunner.ids: org.springframework.cloud.contract.verifier.stubs:streamService:0.0.1-SNAPSHOT:stubs
spring.cloud.contract.stubrunner.stubs-mode: remote
spring:
  cloud:
    stream:
      bindings:
        test1-in-0:
          destination: returnBook
        test1-out-0:
          destination: outputToAssertBook
    function:
      definition: test1

server:
  port: 0

debug: true

要触发来自return_book_1标签,使用以下StubTrigger作为接口 遵循:spring-doc.cadn.net.cn

stubFinder.trigger('return_book_1')

这会向合同输出消息中描述的目的地发送消息。spring-doc.cadn.net.cn

Spring JMS 的消费者端消息传递

Spring Cloud 合同存根 Runner 的消息模块提供了一个简单的方式与 Spring JMS 集成。spring-doc.cadn.net.cn

该集成假设你有一个正在运行的 JMS 代理实例。spring-doc.cadn.net.cn

将跑者加入项目

你需要在类路径上同时放置 Spring JMS 和 Spring Cloud Contract Stub Runner。记得给你的测试类做注释 跟@AutoConfigureStubRunner.spring-doc.cadn.net.cn

例子

假设存根结构如下:spring-doc.cadn.net.cn

├── stubs
    └── bookReturned1.groovy

进一步假设以下测试配置:spring-doc.cadn.net.cn

spring.cloud.contract.stubrunner:
  repository-root: stubs:classpath:/stubs/
  ids: my:stubs
  stubs-mode: remote
spring:
  activemq:
    send-timeout: 1000
  jms:
    template:
      receive-timeout: 1000

现在考虑以下合同:spring-doc.cadn.net.cn

Contract.make {
	label 'return_book_1'
	input {
		triggeredBy('bookReturnedTriggered()')
	}
	outputMessage {
		sentTo('output')
		body('''{ "bookName" : "foo" }''')
		headers {
			header('BOOKNAME', 'foo')
		}
	}
}

要触发来自return_book_1标签,我们使用StubTrigger界面,具体如下:spring-doc.cadn.net.cn

stubFinder.trigger('return_book_1')

这会向合同输出消息中描述的目的地发送消息。spring-doc.cadn.net.cn