mock - 创建新文件(Java)

问题描述 投票:0回答:1

如何检查 如果 不创建新的目录?

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天时间试图覆盖这段代码。

java mockito powermock powermockito easymock
1个回答
2
投票

在你的代码中,将下面的代码提取到一个本地变量中

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);
© www.soinside.com 2019 - 2024. All rights reserved.