33. 测试

Spring Cloud Stream 支持测试您的微服务 applications 而无需连接到消息传递系统。您可以使用spring-cloud-stream-test-support library 提供的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 显示了如何在处理器上测试输入和输出 channels:

@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 和输出 channel 的 application,它们都通过Processor接口绑定。绑定接口被注入到测试中,以便我们可以访问两个 channel。我们在输入 channel 上发送一条消息,我们使用 Spring Cloud Stream 的测试支持提供的MessageCollector来捕获消息已经发送到输出 channel 的结果。收到消息后,我们可以验证 component 是否正常运行。

33.1 禁用测试 Binder 自动配置

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

@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下引用,如下面的 example 所示:

spring.cloud.stream.defaultBinder=test