java - 模拟 - 创建新文件(Java)

标签 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 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/

相关文章:

java - 使用 ScheduledExecutorService 安排 Applet 启动

java - 使用 Mockito 模拟异常 : Unexpected Exception error

java - Mockito - 方法内的测试方法

unit-testing - 如何将 thenAnswer 与返回 void 的方法一起使用

java - 我如何模拟我正在测试的类的继承方法

java - 使用 mockito 模拟类时出现 ClassNotFound 错误

java - 如何将 jar 放在 jetty 类路径的 jetty/lib 中?

java - 是检查错误好还是异常(exception)好

java - 如何在应用 RowFilter 过滤后禁用 jtable 中的列标题排序

java - HConnectionManager.class(HBase)PowerMock期间出现异常