如何通过 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 相关的目标文件的文件权限?
注意
Target source code to test cannot be modified, meaning
Myhandler.class
is a legacy code which is not to be modified.
最佳答案
不依赖于操作系统文件权限,而是使用 PowerMock 模拟 FileUtils.getFile(...) 并使其返回一个 File 实例(例如匿名子类),该实例返回 canWrite()/canRead 的特定值().
关于java - 通过 JUnit 模拟文件读/写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54253429/