你如何通过 JUnit 模拟文件读/写?
这是我的场景
MyHandler.java
public abstract class MyHandler {
private String path = //..path/to/file/here
public synchronized void writeToFile(String infoText) {
// Some processing
// Writing to File Here
File file = FileUtils.getFile(filepath);
file.createNewFile();
// file can't be written, throw FileWriteException
if (file.canWrite()) {
FileUtils.writeByteArrayToFile(file, infoText.getBytes(Charsets.UTF_8));
} else {
throw new FileWriteException();
}
}
public String readFromFile() {
// Reading from File here
String infoText = "";
File file = new File(path);
// file can't be read, throw FileReadException
if (file.canRead()) {
infoText = FileUtils.readFileToString(file, Charsets.UTF_8);
} else {
throw FileReadException();
}
return infoText
}
}
MyHandlerTest.java
@RunWith(PowerMockRunner.class)
@PrepareForTest({
MyHandler.class
})
public class MyHandlerTest {
private static MyHandler handler = null;
// Some Initialization for JUnit (i.e @Before, @BeforeClass, @After, etc)
@Test(expected = FileWriteException.class)
public void writeFileTest() throws Exception {
handler.writeToFile("Test Write!");
}
@Test(expected = FileReadException.class)
public void readFileTest() throws Exception {
handler.readFromFile();
}
}
鉴于上述来源,文件不可写(不允许写权限)的场景是可以的,但是,当我尝试做file不可读的场景时(不允许读权限)。它总是读取文件,我已经尝试通过以下方式修改测试代码的文件权限
File f = new File("..path/to/file/here");
f.setReadable(false);
但是,我做了一些阅读,setReadable()在 Windows 机器上运行时总是返回 false(失败)。
有没有办法以编程方式修改与 JUnit 相关的目标文件的文件权限?
笔记
无法修改要测试的目标源代码,即不能修改 Myhandler.class的遗留代码。
慕侠2389804
慕娘9325324
HUX布斯
相关分类