I suggest you create an interface wrapper around you with IO classes (the PrintWriter class in your case) so that you can use mock objects for output. You do not need to test Java PrintWriter , you want to test your functionality, right?
So your class will be
class MyClass { MyWriter out; public void setOut(MyWriter out) { this.out = out; }
The signature of the MyWriter interface MyWriter quite simple.
interface MyWriter { void println(Object x);
Then you can use EasyMock to record the test. The testing method will look like
@Test public void testWrite() { MyWriter out = EasyMock.createMock(MyWriter.class); EasyMock.expect(mock.println(EasyMock.anyObject())).times(3); EasyMock.expect(mock.close()).times(1); List<FigureGeneral> list = ... list.add(...); list.add(...); list.add(...); replay(mock); MyClass myClass = new MyClass(); myClass.setOut(out); myClass.write("mockFileName", list); verify(mock); }
source share