Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to make log4j error() calls throw an exception in jUnit tests?
    primarykey
    data
    text
    <p>I have a Java project being tested with JUnit (mix of Junit 3 and 4 style), where the classes under test might log a log4j error. I would like to make a unit test fail if such an error is logged.</p> <p>Is there a generic way to configure either log4j or the unit test infrastructure to make any call to a log4j error() method in the code under test throw a runtime exception and therefore fail the test? AOP might be one way, but I'm interested in other possibilities too.</p> <p>The intention here is to weed out places in code where log4j error() is being used incorrectly. That is, when an error is logged but no exception or error handling has occurred, either it's not really an error, or it is and should be raised.</p> <p>eg:</p> <pre><code>public class MyTest extends TestCase { public void testLogAnError() { // Want to make this fail new MyClass().logAnError(); } } public class MyClass() { static Logger logger = Logger.getLogger("foo"); public void logAnError() { // I'm logging an error, but not doing anything about it logger.error("Something bad, or is it?"); // TODO throw an exception or don't log an error if there isn't one } } </code></pre> <p>Update: This is what the solution I'm using currently looks like. It is based on sbridges' answer (added to test class):</p> <pre><code>private static final Appender crashAndBurnAppender = new NullAppender () { public void doAppend(LoggingEvent event) { if(event.getLevel() == Level.ERROR) { throw new AssertionError("logged at error:" + event.getMessage()); } } }; </code></pre> <p>Then in setUp:</p> <pre><code>Logger.getRootLogger().addAppender(crashAndBurnAppender); </code></pre> <p>And tearDown:</p> <pre><code>Logger.getRootLogger().removeAppender(crashAndBurnAppender); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload