开发者

How to make JUnit4 log all unthrown exceptions?

Hey, I'm using SpringJUnit4ClassRunner, and running large suites of tests using the eclipse UI. When tests fail, I can see the exceptions an开发者_如何转开发d the full stack trace in the junit view. I would like them to be also logged.

(Using log4j wrapped by apache.commons.logging)


Extend SpringJUnit4ClassRunner:

public class MySpringJUnit4ClassRunner extends SpringJUnit4ClassRunner{
    @Override
    public void run(RunNotifier notifier) {
    EachTestNotifier testNotifier= new EachTestNotifier(notifier,
            getDescription());
    try {
        Statement statement= classBlock(notifier);
        statement.evaluate();
    } catch (AssumptionViolatedException e) {
        testNotifier.fireTestIgnored();
        Logger.error(e);
    } catch (StoppedByUserException e) {
        Logger.error(e);
        throw e;
    } catch (Throwable e) {
        testNotifier.addFailure(e);
        Logger.error(e);
    }
  }
 //...
}

Then use MySpringJUnit4ClassRunner as your runner.


If you use maven for build, it comes packaged with a sure fire plugin that provides details report on the test cases. In eclipse you could make application console to be logged. I believe it is in runconfig of the application.Although I do not know the exact details.


if you add log4j to your project, you can log the exceptions with:

init logger in your testclass:

 private static final Logger logger = Logger.getLogger(YourClassNameclass);

here the code to log the message:

try{
 your code here...
} catch (SomeException e){
logger.error("Description of your error", e);
}

and here the pattern in your log4j.properties to log the messages in a file:

log4j.rootLogger=ALL,A1

log4j.appender.A1=org.apache.log4j.FileAppender
log4j.appender.A1.File=Testlogfile.log
log4j.appender.A1.append=false
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=\
%-4r [%t] %-5p %c %x -%m%n

good luck! :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜