2

Consider a JUnit method within a JUnit class. It has some tests and some logger.info/debug statements or whatever. Maybe you don't log inside Junit methods, but I do and it saves me lots of hassles for quickly knowing why some tests failed.

I would like to 'erase' those log statements if the method reaches the end, possibly with SLF4J

A simple way to implement that would be to

logger.tick();

Tells logger to flag further log statements.

logger.tack();

Erase all the log statements up to the tick flag. Problem is that you cannot erase stuff on the Eclipse Console ;).

This would make my life much happier now that i'm using Continuous JUnit Testing.

0

1 Answer 1

2

I won't feel self conscious about logging inside unit tests but I imagine most people do alright with the logging facility built into the Unit test framework already. However if you wanted to implement this, you need to capture logs in a variable (some might suggest a StringBuilder) and then dump them at the end of the test based on some dead man's switch (so if the switch isn't hit the last act of the unit test is to dump the held back log).

An example might look like this:

public abstract class LoggedTest extends TestCase {
  protected boolean displayLog;
  protected StringBuilder log;

  public void tick() {
    displayLog = true;
  }

  public void tack() {
    displayLog = false;
  }

  public void log(String msg) {
    log.append(message);
  }

  protected void setUp() {
    displayLog = false;
    log = new StringBuilder();
  }

  protected void tearDown() {
    if(displayLog) {
      System.err.println(log);
    }
  }
}
2
  • Just to add to Jason's idea, you should use StringBuilder() instead - as you might see your unit tests suffering not from your code but from the performance of StringBuffer.
    – KappaMax
    Sep 21, 2012 at 16:52
  • Good edit @r0estir0bbe! :) I'm amazed at the poor quality of code I was writing just two years ago. Hopefully I've gotten better. Jul 23, 2014 at 16:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.