您如何通过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 f = new File("..path/to/file/here");
f.setReadable(false);
但是,我做了一些阅读,setReadable()在Windows计算机上运行时总是返回false(失败).
有没有办法相对于JUnit以编程方式修改目标文件的文件许可权?
注意
Target source code to test cannot be modified,meaning
Myhandler.class
is a legacy code which is not to be modified.
最佳答案