简体   繁体   English

当使用者抛出异常时如何使 JUnit 测试失败?

[英]How to fail JUnit tests when a consumer throws an exception?

We are using Spring and ActiveMQ (JmsTemplate).我们正在使用 Spring 和 ActiveMQ (JmsTemplate)。

We have a very unwanted scenario where the JMS consumer (that handles messages asynchronously) is throwing an exception but the JUnit test is still successfully finished.我们有一个非常不想要的场景,其中 JMS 使用者(异步处理消息)抛出异常,但 JUnit 测试仍然成功完成。

How can we fail all tests whenever an exception is thrown on a different thread than the main test thread?每当在与主测试线程不同的线程上抛出异常时,我们如何使所有测试失败?

You could try JUnit's Rule mechanism to "wrap" each test execution with a custom UncaughtExceptionHandler, recording any uncaught exceptions and failing the test if such exceptions are recorded.您可以尝试 JUnit 的 Rule 机制,用自定义 UncaughtExceptionHandler 来“包装”每个测试执行,记录任何未捕获的异常,如果记录了此类异常,则测试失败。 A nice example can be found here: http://blog.cedarsoft.com/2011/12/junit-rule-fail-tests-on-exceptionsfailed-assertions-in-other-threads/一个很好的例子可以在这里找到: http : //blog.cedarsoft.com/2011/12/junit-rule-fail-tests-on-exceptionsfailed-assertions-in-other-threads/

You can plug on Spring's MessageListenerContainer an ExceptionListener which gets JMSExceptions and an ErrorHandler which gets all other exceptions.您可以在 Spring 的 MessageListenerContainer 上插入一个获取 JMSExceptions 的 ExceptionListener 和一个获取所有其他异常的 ErrorHandler。 Then you can test if this listener has received something or not.然后你可以测试这个监听器是否收到了一些东西。

See AbstractMessageListenerContainer.setExceptionListener and AbstractMessageListenerContainer.setErrorHandler JavaDoc.请参阅AbstractMessageListenerContainer.setExceptionListenerAbstractMessageListenerContainer.setErrorHandler JavaDoc。

If you're not using the MessageListenerContainer but the JmsTemplate.receive method, then this method should raise an unchecked JmsException.如果您不使用 MessageListenerContainer 而是使用 JmsTemplate.receive 方法,则此方法应引发未经检查的 JmsException。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM