35. Testing

Spring Cloud Stream 支持在不连接消息传递系统的情况下测试您的微服务应用程序。您可以使用spring-cloud-stream-test-support库提供的TestSupportBinder来做到这一点,该库可以作为测试依赖项添加到应用程序中,如以下示例所示:

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

Note

TestSupportBinder使用 Spring Boot 自动配置机制来取代在 Classpath 上找到的其他绑定器。因此,在添加 Binder 作为依赖项时,必须确保使用了test范围。

TestSupportBinder使您可以与绑定的 Channels 进行交互,并检查应用程序发送和接收的所有消息。

对于出站消息通道,TestSupportBinder注册一个订户,并将应用程序发出的消息保留在MessageCollector中。在测试期间可以检索它们,并针对它们进行 assert。

您还可以将消息发送到入站消息通道,以便使用者应用程序可以使用消息。以下示例显示了如何在处理器上测试 Importing 和输出通道:

@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";
    }
  }
}

在前面的示例中,我们创建了一个具有 Importing 通道和输出通道的应用程序,它们都通过Processor接口绑定。绑定的接口被注入到测试中,以便我们可以访问两个通道。我们在 Importing 通道上发送一条消息,然后使用 Spring Cloud Stream 的测试支持提供的MessageCollector来捕获消息已作为结果发送到输出通道。收到消息后,我们可以验证组件是否正常运行。

35.1 禁用测试绑定程序自动配置

测试绑定程序背后的目的是取代 Classpath 上的所有其他绑定程序,以使其易于测试您的应用程序而无需更改生产依赖性。在某些情况下(例如,集成测试),使用实际的生产绑定程序很有用,并且需要禁用测试绑定程序自动配置。为此,您可以使用 Spring Boot 自动配置排除机制之一来排除org.springframework.cloud.stream.test.binder.TestSupportBinderAutoConfiguration类,如以下示例所示:

@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 上使用,并且其defaultCandidate属性设置为false,以使其不干扰常规用户配置。可以在名称test下引用它,如以下示例所示:

spring.cloud.stream.defaultBinder=test