Thursday, September 6, 2012

redirecting system.out for purpose testing

In a test I had verify an output on system.out. At first I use slf4j and after reflexion I think about redirecting System.out... It gave the next lines


static private PrintStream currentSystemOut = System.out;
static private List listchar = new ArrayList(); 


....
@BeforeClass static public void setup() {
....
  //redirect system.out  to listchar
  PrintStream printStream;
  OutputStream outs = new OutputStream() {
   @Override
   public void write(int b) throws IOException {
   char c = (char)b;
   listchar.add(new Character(c));
   }
  };
  printStream = new PrintStream(outs);
  System.setOut(printStream);
 }
 
@AfterClass static public void teardown() {
  //revert setting
  System.setOut(currentSystemOut);
 }
 
private static String getOutContent() {
  String res = "";
  for(Character aChar:  listchar ) {
   res = res.concat( aChar +"");
  }
  return res;
 }
...

No comments:

Post a Comment