简体   繁体   中英

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

We are using Spring and 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.

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. A nice example can be found here: 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. Then you can test if this listener has received something or not.

See AbstractMessageListenerContainer.setExceptionListener and AbstractMessageListenerContainer.setErrorHandler JavaDoc.

If you're not using the MessageListenerContainer but the JmsTemplate.receive method, then this method should raise an unchecked JmsException.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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