You are viewing a plain text version of this content. The canonical link for it is here.
Posted to log4j-user@logging.apache.org by Su...@i2.com on 2002/06/19 16:57:36 UTC

sample code to integrate JUnit with Log4J !

Just thought of sharing this piece of code that might be useful to others
trying to integrate junit with ant. All the asserts and fail messages that 
are
send to standard output from the junit tests go into the log4j appenders
specified in the log4j properties file.

//  Just showing the relevant portions from my code

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.framework.TestResult;

import java.io.*;
import java.lang.reflect.Method;
import junit.textui.TestRunner;

import org.apache.log4j.PropertyConfigurator;


  public static void main(String args[])
  {
    try
    {
      String logPropsFile = System.getProperty("log.properties.file");
      PropertyConfigurator.configure(logPropsFile);

      // I use my class name here
      Category LOG = Category.getInstance( SLSTestSuite.class );

      boolean isDebugEnabled = LOG.isDebugEnabled();

      if (isDebugEnabled)
        LOG.debug("logfile = " + logPropsFile);

      String[] testCaseName = {SLSTestSuite.class.getName()};
      ByteArrayOutputStream ba = new ByteArrayOutputStream();
      PrintStream ps = new PrintStream(ba, false);

      class MyTestRunner extends TestRunner {
        public MyTestRunner(java.io.PrintStream writer)
        {
          super(writer);
        }
        public TestResult start(java.lang.String[] args)
                    throws java.lang.Exception
        {
          return super.start(args);
        }
      }

      MyTestRunner aTestRunner= new MyTestRunner(ps);

     // this will invoke the suite method of the testCaseName class.
      TestResult r= aTestRunner.start(testCaseName);

      LOG.info(">> TEST RESULTS SUMMARY !");

      if (  ! r.wasSuccessful()  )  {
        LOG.info("Finished executing the test cases with failures !");
      } else {
        LOG.info("Finished Executing the test cases successfully !");
      }

      ps.flush();

      // this will write to the specified appenders
      LOG.info(ba.toString("utf-8"));

      ba.close();
      ps.close();
    }
    catch(Exception e)
    {
      e.printStackTrace();
      System.err.println(e.getMessage());
      System.exit(-2);
    }

  }// end of main

Sujit