32. 测试

Spring Cloud Stream 支持测试您的微服务 applications 而无需连接到消息传递系统。您可以使用spring-cloud-stream-test-support library 提供的TestSupportBinder来执行此操作,该TestSupportBinder可以作为测试依赖项添加到 application:

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

TestSupportBinder使用 Spring Boot 自动配置机制来取代 classpath 上找到的其他 binders。因此,在添加 binder 作为依赖项时,请确保正在使用test范围。

TestSupportBinder允许用户与绑定的 channels 进行交互,并检查 application 发送和接收的消息

对于出站消息 channels,TestSupportBinder注册单个订户并保留中 application 发出的消息。它们可以在测试期间检索并对它们进行断言。

用户还可以向入站消息 channels 发送消息,以便 consumer application 可以使用消息。以下 example 显示了如何在处理器上测试输入和输出 channel。

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ExampleTest {

  @Autowired
  private Processor processor;

  @Autowired
  private MessageCollector messageCollector;

  @Test
  @SuppressWarnings("unchecked")
  public void testWiring() {
    Message<String> message = new GenericMessage<>("hello");
    processor.input().send(message);
    Message<String> received = (Message<String>) messageCollector.forChannel(processor.output()).poll();
    assertThat(received.getPayload(), equalTo("hello world"));
  }

  @SpringBootApplication
  @EnableBinding(Processor.class)
  public static class MyProcessor {

    @Autowired
    private Processor channels;

    @Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
    public String transform(String in) {
      return in + " world";
    }
  }
}

在上面的例子中,我们正在创建一个具有输入和输出 channel 的 application,它通过Processor接口绑定。绑定接口被注入到测试中,因此我们可以访问两个 channel。我们在输入 channel 上发送一条消息,我们正在使用 Spring Cloud 提供的MessageCollector Stream 测试支持来捕获已经发送到输出 channel 的消息。收到消息后,我们可以验证 component 是否正常运行。

32.1 禁用测试 binder 自动配置

测试 binder 取代 classpath 上所有其他 binders 背后的意图是让您可以轻松测试您的 applications 而无需更改 production 依赖项。在某些情况下(e.g .integration 测试),使用实际的 production binders 非常有用,这需要禁用 test binder 自动配置。在 order 中,您可以使用 Spring Boot 自动配置排除机制之一排除org.springframework.cloud.stream.test.binder.TestSupportBinderAutoConfiguration class,如下面的 example 中所示。

@SpringBootApplication(exclude = TestSupportBinderAutoConfiguration.class)
	@EnableBinding(Processor.class)
	public static class MyProcessor {

		@Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
		public String transform(String in) {
			return in + " world";
		}
	}

禁用自动配置时,classpath 上的 test binder 可用,并且defaultCandidate property 设置为false,因此它不会干扰常规用户 configuration。它可以在 name test e.g 下引用。:

spring.cloud.stream.defaultBinder=test