Spring Binder Unit Test
当我们用消息在中间件之间传递时,很容易使用到spring cloud stream, 而spring又高度集成了spring-cloud-stream-binder来简化代码。
具体逻辑如下:
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
properties
spring.cloud.stream.bindings.process-in-0.destination=from_topic spring.cloud.stream.bindings.process-in-0.group=consumer_1 # GMI Kafka producer spring.cloud.stream.bindings.process-out-0.destination=to_topic
//function
@Bean public Function<Message<FromTopicMsg>, Message<ToTopicMsg>> process(DemoService service) { return fromMessage -> fromMessage.filter(service::isValid).map(service::convert); }
代码简化了很多,然而ut该如何实现呢?
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-kafka-streams</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream</artifactId>
<type>test-jar</type>
<classifier>test-binder</classifier>
</dependency>
@Test
public void testSingleFunction() {
this.context = new SpringApplicationBuilder(TestChannelBinderConfiguration
.getCompleteConfiguration(FunctionsConfiguration.class))
.web(WebApplicationType.NONE)
.run("--spring.cloud.stream.function.definition=toUpperCase",
"--spring.jmx.enabled=false");
InputDestination source = this.context.getBean(InputDestination.class);
OutputDestination target = this.context.getBean(OutputDestination.class);
source.send(new GenericMessage<byte[]>("hello".getBytes(StandardCharsets.UTF_8)));
assertThat(target.receive(1000).getPayload())
.isEqualTo("HELLO".getBytes(StandardCharsets.UTF_8));
//to ensure there is no possibility of load balancing to the EnableBinding
source.send(new GenericMessage<byte[]>("hello".getBytes(StandardCharsets.UTF_8)));
assertThat(target.receive(1000).getPayload())
.isEqualTo("HELLO".getBytes(StandardCharsets.UTF_8));
}
引自:
https://www.programcreek.com/java-api-examples/?api=org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration
浙公网安备 33010602011771号