【问题标题】:mock - creating new files (Java)模拟 - 创建新文件 (Java)
【发布时间】:2020-05-21 18:10:14
【问题描述】:

如何在不创建新目录的情况下检查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 天试图覆盖此代码。

【问题讨论】:

  • 我建议您将您的姓名和术语翻译成英文,这样更容易获得帮助。 @guimas

标签: java mockito powermock powermockito easymock


【解决方案1】:

下面的代码提取到局部变量中

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多