Search code examples
javajunit4easymock

Mock new PrintWriter(String fileName) using EasyMock


My code uses PrintWriter to write a content to file, like

PrintWriter writer = null;
try
{
    writer = new PrintWriter( fileName + "_version", "UTF-8" );
    writer.println( "writing File" );
}
catch( FileNotFoundException e )
{
    e.printStackTrace();
}

I want to write a jUnit test using EasyMock only. How do I mock new object creation of PrintWriter in EasyMock?


Solution

  • You can't test the above code with EasyMock.

    That call to new PrintWriter() inside that try/catch can't be mocked with EasyMock. End of story.

    You will either need PowerMock(ito), or JMockit in order to be able to get control over the result of new().

    Alternatively (and preferred): you should change your hard-to-test production code to something that is easier to test, by using dependency injection for example. One simple approach would be pass a FileWrite object to such code.