我正在尝试为该类编写一个单元测试:
public class ClassToTest
{
public List<String> walk(URI path)
{
List<String> directories= new List<String>();
Path share = Paths.get(path);
try
{
Stream<Path> folders = Files.list(share).filter(Files::isDirectory);
folders.forEach(Path -> {
{
directories.add(Path.toUri());
}
});
}
catch (IOException | SecurityException e)
{
System.out.println("Exception in crawling folder:"+path.toString());
e.printStackTrace();
}
return directories;
}
}
这是我的单元测试:
@RunWith(PowerMockRunner.class)
@PrepareForTest({Files.class, ClassToTest.class })
class ClassToTestUTest
{
@Mock
private Path folder1;
@Mock
private Path folder2;
private ClassToTest underTest;
@BeforeEach
void setUp() throws Exception
{
PowerMockito.mockStatic(Files.class);
}
@Test
void testWalk() throws IOException
{
String sharepath = "\\\\ip\\Share";
Path temp = Paths.get(sharepath);
Stream<Path> folders;
ArrayList<Path> listOfFolders = new ArrayList<Path>();
listOfFolders.add(folder1);
listOfFolders.add(folder2);
folders = listOfFolders.stream();
when(Files.list(any())).thenReturn(folders);
List<String> directories= underTest.walk(temp.toUri());
//Check the directories list.
}
}
当我运行它时,模拟不起作用。我从实际Files.list()
方法中得到一个例外。
我也想模拟 (Paths.class)Paths.get()
调用,但暂时不要这样做。
Junit错误:
java.nio.file.Files.provider(Files.java:97) 在 java.nio.file.Files.newDirectoryStream(Files.java:457) 在 java.nio.file.Files.list( Files.java:3451) 在 com.ClassToTestUTest.testWalk(ClassToTestUTest.java:51)
我发现了很多与模拟这个 Files 类有关的问题。我正在使用 PowerMock 2.0.0 RC4 和 Mockito 2.23.4。
我哪里错了?