0

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?

brass monkey
  • 5,841
  • 10
  • 36
  • 61
Navin a.s
  • 416
  • 2
  • 8
  • 19

2 Answers2

2

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

The real question here is: "What do you want to test?".

Testing and mocking require a tested class and dependencies.

Here there a no visible tested class. If the idea is that you want to test the method creating and using the PrintWriter, yes, other answers are right, you can't. You need PowerMock on top of EasyMock to mock the new.

However, depending on what you are doing, meaningful refactoring will easily solve the problem. So if you give us a more complete example, we will be able to give some more advice.

Henri
  • 5,551
  • 1
  • 22
  • 29