【问题标题】:How to test MANUAL ACK in Spring Stream - RabbitMQ如何在 Spring Stream 中测试 MANUAL ACK - RabbitMQ
【发布时间】:2017-11-19 00:06:00
【问题描述】:

我使用 spring-cloud-stream 作为 RabbitMQ 的包装器。

在我的项目中,我需要使用 MANUAL ACK。所以我添加了适当的配置/代码,当我打开应用程序时它工作。消息被传递,ACK 被消费者发回。

  @StreamListener(target = Sink.INPUT)
  public void foo(@Payload String message,
                  @Header(AmqpHeaders.CHANNEL) Channel channel,
                  @Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag) throws IOException {
    service.bar(message);
    channel.basicAck(deliveryTag, false);
  }

问题是:

我可以为 AUTO ACK 编写测试,但如何为 MANUAL ACK 编写测试?我只是不知道如何通过@Header(AmqpHeaders.CHANNEL) Channel channel在我的测试中?

【问题讨论】:

    标签: spring-cloud-stream


    【解决方案1】:

    好的,我想我已经弄清楚了如何使用 mockito 来做到这一点:

    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
    public class FooTest {
    
      @Autowired
      private Sink sink;
    
      @MockBean
      private BarService barService;
    
      @Test
      public void hello() throws Exception {
        //given
        Channel channel = mock(Channel.class);
        HashMap<String, Object> attributes = new HashMap<>();
        attributes.put(AmqpHeaders.CHANNEL, channel);
        attributes.put(AmqpHeaders.DELIVERY_TAG, 1);
    
        //when
        sink.input().send(MessageBuilder.createMessage("test-message", new MessageHeaders(attributes)));
    
        //then
        verify(barService).bar("test-message");
        verify(channel).basicAck(1, false);
      }
    
    }
    

    但也许有人知道是否有可能的方法而不模拟标题中的Channel

    【讨论】:

      【解决方案2】:

      对于你的监听器方法的单元测试,你可以直接用 mock 调用它

      foo("test-message", channel, 1L);
      

      发送消息也会测试基础架构,例如,如果您依赖框架的消息转换(即发送 JSON 并具有 POJO @Payload 参数),您可能想要这样做。

      【讨论】:

      • 单元测试不是我的情况。我想要进行集成测试,它还将检查我的队列配置是否正确。所以我需要通过通道发送消息,而不是直接调用处理方法。
      • 在这种情况下,不清楚您在回答“但也许有人知道是否有可能的方法而不在标题中模拟 Channel?”的补充问题中问的是什么。你的做法是正确的。
      • 只是好奇是否可以在不模拟频道的情况下做到这一点,那么如何让 RabbitMq 发送真实频道。
      猜你喜欢
      • 2018-12-17
      • 2018-01-24
      • 2018-06-20
      • 2020-07-07
      • 1970-01-01
      • 2012-04-22
      • 2018-11-06
      • 2015-05-01
      • 1970-01-01
      相关资源
      最近更新 更多