通过 JUnit 模拟文件读/写

你如何通过 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的遗留代码。


白衣非少年
浏览 159回答 3
3回答

慕侠2389804

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

慕娘9325324

由于 Mockito 不能模拟静态方法,请改用File工厂(或将您重构FileUtils为工厂),然后您可以模拟它并返回一个模拟File实例,您还可以在其中模拟File您想要的任何方法。因此,FileUtils.getFile(filepath)您现在将拥有类似的东西FileFactory.getInstance().getFile(filepath),例如,您可以getFile(String)轻松地模拟方法。

HUX布斯

在 jUnit 中,对于像你这样的场景有一个方便的规则。public class MyHandlerTest {    @Rule    // creates a temp folder that will be removed after each test    public org.junit.rules.TemporaryFolder folder = new org.junit.rules.TemporaryFolder();    private MyHandler handler;    @Before    public void setUp() throws Exception {        File file = folder.newFile("myFile.txt");        // do whatever you need with it - fill with test content and so on.        handler = new MyHandler(file.getAbsolutePath()); // use the real thing    }    // Test whatever behaviour you need with a real file and predefined dataset.}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java