Search code examples
javamockitopowermockpowermockitoeasymock

mock - creating new files (Java)


how to check if without creating a new directory?

String st = "exemple";
String path = "exemple";

if (!new File(path).exists() && !new File(path).mkdirs()) {
    throw new ComumException("trocaarquivos.erro.exemple", path);
}

my attempts:

@PrepareForTest(File.class )

 File myFile = PowerMockito.mock(File.class);
 PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(myFile);
 PowerMockito.when(!new File(anyString()).exists() && !new File(anyString()).mkdirs()).thenReturn(true);

and

Mockito.when(myFile.exists()).thenReturn(true);
Mockito.when(myFile.mkdirs()).thenReturn(true);

3 days trying to cover this code.


Solution

  • inside ur code extract below into a local variable

    File f= new File(path);
    

    also in the test code

    @PrepareForTest(File.class ) //Here instead of File it should be the class where new file is created, i.e. YourClass.class
    

    i.e.

    @PrepareForTest(ClassYoureCreatingTheFileInstanceIn.class)
    

    now below code should work

    File myFile = PowerMockito.mock(File.class);
     PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(myFile);
    Mockito.when(myFile.exists()).thenReturn(true);
    Mockito.when(myFile.mkdirs()).thenReturn(true);