1

Possible Duplicate:
JUnit test for System.out.println()

Is it possible to check, through JUnit testing, if the method System.out.println("One, Two"), actually prints One, Two?

Community
  • 1
  • 1
FranXh
  • 4,481
  • 20
  • 59
  • 78
  • 3
    see http://stackoverflow.com/questions/1119385/junit-test-for-system-out-println – Kai Sternad May 12 '12 at 06:21
  • @bunting That's would do the stuff, but I would recommend that aproach only and only if you can't refactor the code. If you are testing new code this look like a code smell. – rsan May 12 '12 at 06:38
  • You want to test Java core library method? Why? – k.m May 12 '12 at 17:42

2 Answers2

3

Yes you can, you could change the default System.out to a file, a buffer, etc. and unit test that new stream for the expected data. But IMO that's a terrible terrible idea.

Other aproach woud be using a Logger instead the standard output and unit test the log, but once again it sounds weird unit testing a logger. At least if you are not developing a logging tool :)

To me it sounds like a bad understanding of what is unit testig, but I could be wrong.

rsan
  • 1,887
  • 2
  • 17
  • 23
  • I do understand what is Unit testing, and I can easily convert the system.out.println to an array, list, or any kind of container, which would be easier to test. just wandering if the method itself can be tested. – FranXh May 12 '12 at 06:45
0

A better idea would be to change your application to be more testable by not using System.out directly.

  • If the method you are trying to test is designed to write output for end users, modify it or the enclosing class so that the destination OutputStream or PrintWriter or whatever is a parameter.

  • On the other hand, if the method is producing log output, use a proper logging framework ... and consider whether it is worthwhile to unit test the log output at all.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216