我有这个类:
public class FooFileRepo {
@Override
public File getDirectory(String directoryPath) {
...
File directory = new File(directoryPath);
...
return directory;
}
@Override
public void mkdirs(File f) {
...
f.getParentFile().mkdirs();
}
public void writeFile(String path, String content) throws FileNotFoundException, UnsupportedEncodingException{
...
try (PrintWriter writer = new PrintWriter(path, "UTF-8");) {
writer.println(content);
}
}
}
如何模拟文件系统操作,以编写此类的单元测试?
谢谢。
使用 PowerMock
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Printwriter.class })
public class SampleTestClass {
@Mock
private PrintWriter mockPrintWriter;
@Before
public void init() throws Exception {
PowerMockito.mockStatic(FileUtils.class);
}
@Test
public void test() throws IOException {
}
}
对于如此简单的测试,最好使用真实的文件系统。作为替代方案,您可以构建一个立面档案操作并轻松模拟此立面。
https://junit.org/junit4/javadoc/4.12/org/junit/rules/temporaryfolder.html
public static class HasTempFolder {
@Rule
public TemporaryFolder folder= new TemporaryFolder();
@Test
public void testUsingTempFolder() throws IOException {
File createdFile= folder.newFile("myfile.txt");
File createdFolder= folder.newFolder("subfolder");
// ...
}
}
还请阅读以下答案:https://stackoverflow.com/a/17164103/516167