java-通过JUnit模拟文件读取/写入

前端之家收集整理的这篇文章主要介绍了java-通过JUnit模拟文件读取/写入 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

您如何通过JUnit模拟文件读取/写入?

这是我的情况

MyHandler.java

  1. public abstract class MyHandler {
  2. private String path = //..path/to/file/here
  3. public synchronized void writeToFile(String infoText) {
  4. // Some processing
  5. // Writing to File Here
  6. File file = FileUtils.getFile(filepath);
  7. file.createNewFile();
  8. // file can't be written,throw FileWriteException
  9. if (file.canWrite()) {
  10. FileUtils.writeByteArrayToFile(file,infoText.getBytes(Charsets.UTF_8));
  11. } else {
  12. throw new FileWriteException();
  13. }
  14. }
  15. public String readFromFile() {
  16. // Reading from File here
  17. String infoText = "";
  18. File file = new File(path);
  19. // file can't be read,throw FileReadException
  20. if (file.canRead()) {
  21. infoText = FileUtils.readFileToString(file,Charsets.UTF_8);
  22. } else {
  23. throw FileReadException();
  24. }
  25. return infoText
  26. }
  27. }

MyHandlerTest.java

  1. @RunWith(PowerMockRunner.class)
  2. @PrepareForTest({
  3. MyHandler.class
  4. })
  5. public class MyHandlerTest {
  6. private static MyHandler handler = null;
  7. // Some Initialization for JUnit (i.e @Before,@BeforeClass,@After,etc)
  8. @Test(expected = FileWriteException.class)
  9. public void writeFileTest() throws Exception {
  10. handler.writeToFile("Test Write!");
  11. }
  12. @Test(expected = FileReadException.class)
  13. public void readFileTest() throws Exception {
  14. handler.readFromFile();
  15. }
  16. }

鉴于以上来源,当文件不可写(不允许写许可)时,方案是可以的,但是,当我尝试执行文件不可读(不允许读许可)的方案时.它总是读取文件,我已经尝试通过以下方式修改测试代码上的文件权限

  1. File f = new File("..path/to/file/here");
  2. 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()的特定值.

Mocking static methods with Mockito

猜你在找的Java相关文章