Q:

Mocking a File using Mockito and PowerMockito

I am writing a JUnit test case for a method that uses FileWriter to create a file but the file physically doesn't exist. I am using PowerMockito to mock the File Object without creating a real file. My test passes but it still creates a file by the name of Mock for file,hashCode in the context root of the project. Is there a way to avoid creating this file? There are some similar questions but not very clear why this is happening.So, while debugging I found out that when the code reaches to new FileWriter the file is created.
Thanks,
JUnit test:
@Test
public void testCreateCSVFile() throws Exception {
    File mockFile = Mockito.mock(File.class);
    PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(mockFile);
    rest of the test...
}

Method under test:
public void createCSVFile(List<IUiIntegrationDto> intgList, String fileName) throws Exception { 
     FileWriter fileWriter = new FileWriter(fileName);
     rest of the code...
}

A:

You are mocking the wrong field. you need to mock FileWriter - this is the one that does the actual file writting

