如何在不创建新目录的情况下检查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);
和
Mockito.when(myFile.exists()).thenReturn(true);
Mockito.when(myFile.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
即
@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);
关于java - 模拟 - 创建新文件(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61941022/