加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 19:25:16 所属栏目:Java 来源:网络整理
导读:您如何通过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

您如何通过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.

最佳答案
不用依赖操作系统文件权限,而是使用PowerMock模拟FileUtils.getFile(…)并使其返回File的实例(例如匿名子类),该实例返回canWrite()/ canRead()的特定值.

Mocking static methods with Mockito

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读