【问题标题】:How to fail JUnit tests when a consumer throws an exception?当消费者抛出异常时如何使 JUnit 测试失败?
【发布时间】:2014-04-30 18:28:36
【问题描述】:

我们正在使用 Spring 和 ActiveMQ (JmsTemplate)。

我们有一个非常不受欢迎的场景,JMS 使用者(异步处理消息)抛出异常,但 JUnit 测试仍然成功完成。

当与主测试线程不同的线程上抛出异常时,我们如何使所有测试失败?

【问题讨论】:

    标签: java spring junit jms activemq


    【解决方案1】:

    您可以尝试使用 JUnit 的 Rule 机制,使用自定义 UncaughtExceptionHandler “包装”每个测试执行,记录任何未捕获的异常,如果记录了此类异常,则测试失败。 一个很好的例子可以在这里找到:http://blog.cedarsoft.com/2011/12/junit-rule-fail-tests-on-exceptionsfailed-assertions-in-other-threads/

    【讨论】:

    【解决方案2】:

    您可以在 Spring 的 MessageListenerContainer 上插入一个获取 JMSExceptions 的 ExceptionListener 和一个获取所有其他异常的 ErrorHandler。然后你可以测试这个监听器是否收到了一些东西。

    请参阅 AbstractMessageListenerContainer.setExceptionListenerAbstractMessageListenerContainer.setErrorHandler JavaDoc。

    如果您使用的不是 MessageListenerContainer 而是 JmsTemplate.receive 方法,那么 此方法应引发未经检查的 JmsException。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 2017-10-28
      • 2011-01-15
      • 2019-04-16
      相关资源
      最近更新 更多