模拟-创建新文件(Java)

模拟-创建新文件(Java),java,mockito,powermock,powermockito,easymock,Java,Mockito,Powermock,Powermockito,Easymock,如何在不创建新目录的情况下检查if String st = "exemple"; String path = "exemple"; if (!new File(path).exists() && !new File(path).mkdirs()) { throw new ComumException("trocaarquivos.erro.exemple", path); } 我的尝试: @PrepareForTest(File.class ) File myFi

如何在不创建新目录的情况下检查if

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

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

@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);


3天尝试覆盖此代码。

在您的代码中,将下面的代码提取到局部变量中

File f= new File(path);
也在测试代码中

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

现在下面的代码应该可以工作了

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);

我建议你把你的名字和术语翻译成英语,这样会更容易得到帮助@吉姆斯
@PrepareForTest(ClassYoureCreatingTheFileInstanceIn.class)
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);