我上了这个课:
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);
}
}
}
如何为编写此类的单元测试而模拟文件系统操作?
谢谢。
答案 0 :(得分:0)
使用 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 {
}
}
答案 1 :(得分:0)
对于这样一个简单的测试,最好使用真实的文件系统。或者,您可以构建外观来进行文件操作并轻松模拟该外观。
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");
// ...
}
}