对于最新稳定版本,请使用spring-cloud-stream 5.0.1spring-doc.cadn.net.cn

测试

Spring Cloud Stream 为在不连接到消息系统的情况下测试您的微服务应用程序提供支持。spring-doc.cadn.net.cn

Spring 集成测试绑定器

Spring Cloud Stream 带有一个测试绑定器,可用于在无需实际的世界绑定器实现或消息代理的情况下测试各种应用程序组件。spring-doc.cadn.net.cn

此测试绑定器充当单元测试和集成测试之间的桥梁,基于Spring 集成框架作为 JVM 内的消息代理,本质上为你提供了两全其美的效果——一个真实的绑定器而无需网络连接。spring-doc.cadn.net.cn

测试绑定器配置

要启用 Spring 集成测试绑定器,您需要将其添加为依赖项,并使用 @EnableTestBinder 注解您的类。spring-doc.cadn.net.cn

添加所需的依赖项spring-doc.cadn.net.cn

下面是所需Maven POM条目的示例。spring-doc.cadn.net.cn

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-stream-test-binder</artifactId>
	<scope>test</scope>
</dependency>

或者对于build.gradle.ktsspring-doc.cadn.net.cn

testImplementation("org.springframework.cloud:spring-cloud-stream-test-binder")

测试绑定器用法

现在,您可以将微服务作为简单的单元测试来测试。
要启用测试绑定器,请使用@EnableTestBinder注释您的类。spring-doc.cadn.net.cn

@SpringBootTest
public class SampleStreamTests {

	@Autowired
	private InputDestination input;

	@Autowired
	private OutputDestination output;

	@Test
	public void testEmptyConfiguration() {
		this.input.send(new GenericMessage<byte[]>("hello".getBytes()));
		assertThat(output.receive().getPayload()).isEqualTo("HELLO".getBytes());
	}

	@SpringBootApplication
	@EnableTestBinder
	public static class SampleConfiguration {
		@Bean
		public Function<String, String> uppercase() {
			return v -> v.toUpperCase();
		}
	}
}

如果您需要更多控制,或希望在同一测试套件中测试多个配置 您可以执行以下操作:<br/>spring-doc.cadn.net.cn

@EnableAutoConfiguration
public static class MyTestConfiguration {
	@Bean
	public Function<String, String> uppercase() {
			return v -> v.toUpperCase();
	}
}

. . .

@Test
public void sampleTest() {
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
				TestChannelBinderConfiguration.getCompleteConfiguration(
						MyTestConfiguration.class))
				.run("--spring.cloud.function.definition=uppercase")) {
		InputDestination source = context.getBean(InputDestination.class);
		OutputDestination target = context.getBean(OutputDestination.class);
		source.send(new GenericMessage<byte[]>("hello".getBytes()));
		assertThat(target.receive().getPayload()).isEqualTo("HELLO".getBytes());
	}
}

当您有多个绑定和/或多个输入和输出时,或者只是想明确指定要发送到的目标名称或接收来自的目标名称,则覆盖send()receive()方法以及InputDestinationOutputDestination类的方法以允许您提供输入和输出目标的名称。spring-doc.cadn.net.cn

考虑以下示例:spring-doc.cadn.net.cn

@EnableAutoConfiguration
public static class SampleFunctionConfiguration {

	@Bean
	public Function<String, String> uppercase() {
		return value -> value.toUpperCase();
	}

	@Bean
	public Function<String, String> reverse() {
		return value -> new StringBuilder(value).reverse().toString();
	}
}

并且实际测试spring-doc.cadn.net.cn

@Test
public void testMultipleFunctions() {
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(
					SampleFunctionConfiguration.class))
							.run("--spring.cloud.function.definition=uppercase;reverse")) {

		InputDestination inputDestination = context.getBean(InputDestination.class);
		OutputDestination outputDestination = context.getBean(OutputDestination.class);

		Message<byte[]> inputMessage = MessageBuilder.withPayload("Hello".getBytes()).build();
		inputDestination.send(inputMessage, "uppercase-in-0");
		inputDestination.send(inputMessage, "reverse-in-0");

		Message<byte[]> outputMessage = outputDestination.receive(0, "uppercase-out-0");
		assertThat(outputMessage.getPayload()).isEqualTo("HELLO".getBytes());

		outputMessage = outputDestination.receive(0, "reverse-out-0");
		assertThat(outputMessage.getPayload()).isEqualTo("olleH".getBytes());
	}
}

在存在诸如 destination 的附加映射属性的情况下,应使用这些名称。例如,考虑前面测试的另一种版本,在该版本中我们显式地将 uppercase 函数的输入和输出映射到 myInputmyOutput 绑定名称:spring-doc.cadn.net.cn

@Test
public void testMultipleFunctions() {
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(
					SampleFunctionConfiguration.class))
							.run(
							"--spring.cloud.function.definition=uppercase;reverse",
							"--spring.cloud.stream.bindings.uppercase-in-0.destination=myInput",
							"--spring.cloud.stream.bindings.uppercase-out-0.destination=myOutput"
							)) {

		InputDestination inputDestination = context.getBean(InputDestination.class);
		OutputDestination outputDestination = context.getBean(OutputDestination.class);

		Message<byte[]> inputMessage = MessageBuilder.withPayload("Hello".getBytes()).build();
		inputDestination.send(inputMessage, "myInput");
		inputDestination.send(inputMessage, "reverse-in-0");

		Message<byte[]> outputMessage = outputDestination.receive(0, "myOutput");
		assertThat(outputMessage.getPayload()).isEqualTo("HELLO".getBytes());

		outputMessage = outputDestination.receive(0, "reverse-out-0");
		assertThat(outputMessage.getPayload()).isEqualTo("olleH".getBytes());
	}
}

测试绑定器和可轮询消息源

Spring 集成测试绑定器还允许您在使用 PollableMessageSource 编写测试时(有关详细信息,请参阅[使用轮询消费者])。spring-doc.cadn.net.cn

然而需要理解的重要一点是轮询不是事件驱动的,PollableMessageSource是一种策略,它暴露了操作以产生(轮询)消息(单数)。你轮询的频率、使用的线程数量以及从何处轮询(消息队列或文件系统)完全由你自己决定;换句话说,配置轮询器、线程或实际的消息源是你的责任。幸运的是Spring提供了大量的抽象来精确地配置这些内容。spring-doc.cadn.net.cn

让我们来看一个示例:spring-doc.cadn.net.cn

@Test
public void samplePollingTest() {
	ApplicationContext context = new SpringApplicationBuilder(SamplePolledConfiguration.class)
				.web(WebApplicationType.NONE)
				.run("--spring.jmx.enabled=false", "--spring.cloud.stream.pollable-source=myDestination");
	OutputDestination destination = context.getBean(OutputDestination.class);
	System.out.println("Message 1: " + new String(destination.receive().getPayload()));
	System.out.println("Message 2: " + new String(destination.receive().getPayload()));
	System.out.println("Message 3: " + new String(destination.receive().getPayload()));
}

@EnableTestBinder
@EnableAutoConfiguration
public static class SamplePolledConfiguration {
	@Bean
	public ApplicationRunner poller(PollableMessageSource polledMessageSource, StreamBridge output, TaskExecutor taskScheduler) {
		return args -> {
			taskScheduler.execute(() -> {
				for (int i = 0; i < 3; i++) {
					try {
						if (!polledMessageSource.poll(m -> {
							String newPayload = ((String) m.getPayload()).toUpperCase();
							output.send("myOutput", newPayload);
						})) {
							Thread.sleep(2000);
						}
					}
					catch (Exception e) {
						// handle failure
					}
				}
			});
		};
	}
}

上面(非常基础的)示例将在2秒间隔内向输出目标Source发送3条消息,该绑定器将它们发送到OutputDestination,我们在那里获取它们(用于任何断言)。目前,它打印如下内容:spring-doc.cadn.net.cn

Message 1: POLLED DATA
Message 2: POLLED DATA
Message 3: POLLED DATA

正如您所见,数据是相同的。这是因为此绑定器定义了实际MessageSource的默认实现——消息通过poll()操作从中轮询。虽然对于大多数测试场景来说已经足够,但在某些情况下,您可能希望定义自己的MessageSource。为此,在您的测试配置中只需配置类型为MessageSource的bean,并提供您自己的消息源实现即可。spring-doc.cadn.net.cn

这是一个例子:spring-doc.cadn.net.cn

@Bean
public MessageSource<?> source() {
	return () -> new GenericMessage<>("My Own Data " + UUID.randomUUID());
}

渲染以下输出;spring-doc.cadn.net.cn

Message 1: MY OWN DATA 1C180A91-E79F-494F-ABF4-BA3F993710DA
Message 2: MY OWN DATA D8F3A477-5547-41B4-9434-E69DA7616FEE
Message 3: MY OWN DATA 20BF2E64-7FF4-4CB6-A823-4053D30B5C74
不要将此bean命名为messageSource,因为它会与Spring Boot提供的同名bean(不同类型)发生冲突,尽管原因无关。