簡體   English   中英

通過測試從Spring Cloud Stream連接到Message Broker

[英]Connect to message broker with Spring cloud stream from test

有一些文章介紹了如何在不連接具有spring-cloud-stream-test-support的消息傳遞系統的情況下測試Spring雲流應用程序。 但是我想從集成測試中真正連接到RabbitMQ,並且不能這樣做。 這是測試類:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EnableBinding(Source.class)
public class StreamIT {

  @Autowired
  private Source source;

  @Test
  public void testMessageSending() throws InterruptedException {
    source.output().send(MessageBuilder.withPayload("test").build());
    System.out.println("Message sent.");
  }

}

一切都與@SpringBootApplication中的相同,它們使用application.yml中的相同屬性。

但是沒有發送消息的日志行( osarcCachingConnectionFactory : Created new connection: SpringAMQP#22e79d25:0/SimpleConnection@5cce3ab6 [delegate=amqp://guest@127.0.1.1:5672/, localPort= 60934] ),甚至如果未啟動代理,則沒有java.net.ConnectException: Connection refused (Connection refused)

難道我做錯了什么? 創建與代理的真實連接並從測試發送消息需要什么?

編輯

您需要從pom中移除測試支持罐。 它的存在(在測試范圍內)是觸發用測試粘合劑替換實際粘合劑的原因。

卸下測試粘合劑支架后,這對我來說效果很好...

@RunWith(SpringRunner.class)
@SpringBootTest
public class So49816044ApplicationTests {

    @Autowired
    private Source source;

    @Autowired
    private AmqpAdmin admin;

    @Autowired
    private RabbitTemplate template;

    @Test
    public void test() {
        // bind an autodelete queue to the destination exchange
        Queue queue = this.admin.declareQueue();
        this.admin.declareBinding(new Binding(queue.getName(), DestinationType.QUEUE, "mydest", "#", null));

        this.source.output().send(new GenericMessage<>("foo"));

        this.template.setReceiveTimeout(10_000);
        Message received = template.receive(queue.getName());
        assertThat(received.getBody()).isEqualTo("foo".getBytes());
    }

}

雖然沒有兔子樣品; 有一個使用真正的(嵌入式)kafka粘合劑進行測試kafka樣本 ,盡管測試罐被排除在外,但並沒有明確指出這是必需的。

由於您在測試中使用@SpringBootTest批注,因此Spring Boot將評估所有可用的自動配置。

如果您的測試類路徑中有spring-cloud-stream-test-support依賴項,那么還將評估以下自動配置:

  • org.springframework.cloud.stream.test.binder.TestSupportBinderAutoConfiguration
  • org.springframework.cloud.stream.test.binder.MessageCollectorAutoConfiguration

結果,在應用程序上下文中只有一個活頁夾org.springframework.cloud.stream.test.binder.TestSupportBinder 用它的名字,您可以理解它對真正的綁定沒有任何作用。

從測試類路徑中排除/刪除spring-cloud-stream-test-support依賴項是一個令人懷疑的解決方案。 由於它會迫使您為單元測試和集成測試創建兩個單獨的模塊。

如果要在測試中排除先前提到的自動配置。 您可以按照以下步驟進行操作:

@RunWith(SpringRunner.class)
@SpringBootTest
@EnableAutoConfiguration(exclude = {TestSupportBinderAutoConfiguration.class, MessageCollectorAutoConfiguration.class})
public class StreamIT {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM