訊息傳遞

Spring Cloud Contract 允許你驗證使用訊息傳遞作為通訊手段的應用。本文件中顯示的所有整合都與 Spring 配合使用,但你也可以建立自己的整合並使用。

訊息傳遞 DSL 頂層元素

訊息傳遞的 DSL 與側重於 HTTP 的 DSL 略有不同。以下各節解釋了這些差異。

由方法觸發的輸出

輸出訊息可以透過呼叫一個方法(例如契約啟動時以及訊息傳送時的 Scheduler)觸發,如下例所示。

Groovy
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

在前面的示例中,如果呼叫了名為 bookReturnedTriggered 的方法,則輸出訊息會發送到 output。在訊息釋出者端,我們生成一個測試,該測試呼叫該方法來觸發訊息。在消費者端,你可以使用 some_label 來觸發訊息。

消費者/生產者

本節僅對 Groovy DSL 有效。

在 HTTP 中,你有 client/stubserver/test 的概念。你也可以在訊息傳遞中使用這些範例。此外,Spring Cloud Contract Verifier 還提供了 consumerproducer 方法(請注意,你可以使用 $value 方法來提供 consumerproducer 部分)。

通用

inputoutputMessage 部分中,你可以呼叫 assertThat,傳入你在基類或靜態匯入中定義的 method 名稱(例如,assertThatMessageIsOnTheQueue())。Spring Cloud Contract 會在生成的測試中執行該方法。

整合

你可以使用以下整合配置之一

  • Apache Camel

  • Spring Integration

  • Spring Cloud Stream

  • Spring JMS

由於我們使用了 Spring Boot,如果你已將其中一個庫新增到類路徑中,所有訊息傳遞配置都會自動設定。

記得在生成的測試的基類上新增 @AutoConfigureMessageVerifier 註解。否則,Spring Cloud Contract 的訊息傳遞部分將無法工作。

如果你想使用 Spring Cloud Stream,請記得新增對 org.springframework.cloud:spring-cloud-stream 的測試依賴,如下所示

Maven
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-stream</artifactId>
    <type>test-jar</type>
    <scope>test</scope>
    <classifier>test-binder</classifier>
</dependency>
Gradle
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。它們定義瞭如何傳送和接收訊息。

在測試中,你可以注入 ContractVerifierMessageExchange 來發送和接收符合契約的訊息。然後將 @AutoConfigureMessageVerifier 新增到你的測試中。以下示例展示瞭如何做到這一點。

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

  @Autowired
  private MessageVerifier verifier;
  ...
}
如果你的測試也需要存根,那麼 @AutoConfigureStubRunner 就包含了訊息傳遞配置,所以你只需要這一個註解即可。

生產者端訊息測試生成

在 DSL 中包含 inputoutputMessage 部分會在釋出者端生成測試。預設情況下,會建立 JUnit 4 測試。但是,也可以建立 JUnit 5、TestNG 或 Spock 測試。

傳遞給 messageFromsentTo 的目標對於不同的訊息傳遞實現可能有不同的含義。對於 Stream 和 Integration,它首先被解析為通道的 destination。然後,如果不存在這樣的 destination,則解析為通道名稱。對於 Camel,它是一個特定的元件(例如 jms)。

考慮以下契約

Groovy
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

對於前面的示例,將建立以下測試

JUnit
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import org.junit.Test;
import org.junit.Rule;
import javax.inject.Inject;
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 {
	@Inject ContractVerifierMessaging contractVerifierMessaging;
	@Inject 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");
	}

}
Spock
import com.jayway.jsonpath.DocumentContext
import com.jayway.jsonpath.JsonPath
import spock.lang.Specification
import javax.inject.Inject
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 {
	@Inject ContractVerifierMessaging contractVerifierMessaging
	@Inject 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 中。然後,它在消費者端被解析,並建立相應的存根路由。

如果類路徑中有多個框架,Stub Runner 需要定義應該使用哪個框架。假設你的類路徑中有 AMQP、Spring Cloud Stream 和 Spring Integration,並且你想使用 Spring AMQP。那麼你需要設定 stubrunner.stream.enabled=falsestubrunner.integration.enabled=false。這樣,唯一剩下的框架就是 Spring AMQP。

存根觸發

要觸發訊息,請使用 StubTrigger 介面,如下例所示

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,因此在你的測試中只需要其中一個即可。

StubTrigger 提供了以下選項來觸發訊息

按標籤觸發

以下示例展示瞭如何使用標籤觸發訊息

stubFinder.trigger('return_book_1')

按 Group ID 和 Artifact ID 觸發

以下示例展示瞭如何按 Group ID 和 Artifact ID 觸發訊息

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

按 Artifact ID 觸發

以下示例展示瞭如何從 Artifact ID 觸發訊息

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

觸發所有訊息

以下示例展示瞭如何觸發所有訊息

stubFinder.trigger()

消費者端訊息傳遞與 Apache Camel

Spring Cloud Contract Stub Runner 的訊息傳遞模組提供了與 Apache Camel 整合的簡便方法。對於提供的 artifacts,它會自動下載存根並註冊所需的路由。

將 Apache Camel 新增到專案

你可以在類路徑中同時包含 Apache Camel 和 Spring Cloud Contract Stub Runner。記得使用 @AutoConfigureStubRunner 註解標記你的測試類。

停用此功能

如果你需要停用此功能,請設定 stubrunner.camel.enabled=false 屬性。

示例

假設我們有以下 Maven 倉庫,其中部署了 camelService 應用的存根

└── .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

此外,假設存根包含以下結構

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

現在考慮以下契約

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 介面,如下所示

stubFinder.trigger("return_book_1")

這將把訊息傳送到契約的輸出訊息中描述的目標。

消費者端訊息傳遞與 Spring Integration

Spring Cloud Contract Stub Runner 的訊息傳遞模組提供了與 Spring Integration 整合的簡便方法。對於提供的 artifacts,它會自動下載存根並註冊所需的路由。

將 Runner 新增到專案

你可以在類路徑中同時包含 Spring Integration 和 Spring Cloud Contract Stub Runner。記得使用 @AutoConfigureStubRunner 註解標記你的測試類。

停用此功能

如果你需要停用此功能,請設定 stubrunner.integration.enabled=false 屬性。

示例

假設你擁有以下 Maven 倉庫,其中部署了 integrationService 應用的存根

└── .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

此外,假設存根包含以下結構

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

考慮以下契約

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

現在考慮以下 Spring Integration 路由

<?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 介面,如下所示

stubFinder.trigger('return_book_1')

這將把訊息傳送到契約的輸出訊息中描述的目標。

消費者端訊息傳遞與 Spring Cloud Stream

Spring Cloud Contract Stub Runner 的訊息傳遞模組提供了與 Spring Stream 整合的簡便方法。對於提供的 artifacts,它會自動下載存根並註冊所需的路由。

如果 Stub Runner 與 Stream 整合時,messageFromsentTo 字串首先被解析為通道的 destination,並且不存在這樣的 destination,則該目標將被解析為通道名稱。

如果你想使用 Spring Cloud Stream,請記得新增對 org.springframework.cloud:spring-cloud-stream 測試支援的依賴,如下所示

Maven
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-stream-test-binder</artifactId>
    <scope>test</scope>
</dependency>
Gradle
testImplementation('org.springframework.cloud:spring-cloud-stream-test-binder')

將 Runner 新增到專案

你可以在類路徑中同時包含 Spring Cloud Stream 和 Spring Cloud Contract Stub Runner。記得使用 @AutoConfigureStubRunner 註解標記你的測試類。

停用此功能

如果你需要停用此功能,請設定 stubrunner.stream.enabled=false 屬性。

示例

假設你擁有以下 Maven 倉庫,其中部署了 streamService 應用的存根

└── .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

此外,假設存根包含以下結構

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

考慮以下契約

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

現在考慮以下 Spring Cloud Stream 函式配置

@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 配置

stubrunner.repositoryRoot: classpath:m2repo/repository/
stubrunner.ids: org.springframework.cloud.contract.verifier.stubs:streamService:0.0.1-SNAPSHOT:stubs
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 介面,如下所示

stubFinder.trigger('return_book_1')

這將把訊息傳送到契約的輸出訊息中描述的目標。

消費者端訊息傳遞與 Spring JMS

Spring Cloud Contract Stub Runner 的訊息傳遞模組提供了與 Spring JMS 整合的簡便方法。

此整合假設你有一個正在執行的 JMS 訊息代理例項。

將 Runner 新增到專案

你的類路徑中需要同時包含 Spring JMS 和 Spring Cloud Contract Stub Runner。記得使用 @AutoConfigureStubRunner 註解標記你的測試類。

示例

假設存根結構如下所示

├── stubs
    └── bookReturned1.groovy

此外,假設以下測試配置

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

現在考慮以下契約

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

要從 return_book_1 標籤觸發訊息,我們使用 StubTrigger 介面,如下所示

stubFinder.trigger('return_book_1')

這將把訊息傳送到契約的輸出訊息中描述的目標。