3 回答

TA貢獻1719條經(jīng)驗 獲得超6個贊
不依賴于操作系統(tǒng)文件權限,而是使用 PowerMock 模擬 FileUtils.getFile(...) 并使其返回 File 的實例(例如匿名子類),該實例返回 canWrite()/canRead() 的特定值。

TA貢獻1783條經(jīng)驗 獲得超4個贊
由于 Mockito 不能模擬靜態(tài)方法,請改用File
工廠(或?qū)⒛貥?gòu)FileUtils
為工廠),然后您可以模擬它并返回一個模擬File
實例,您還可以在其中模擬File
您想要的任何方法。
因此,FileUtils.getFile(filepath)
您現(xiàn)在將擁有類似的東西FileFactory.getInstance().getFile(filepath)
,例如,您可以getFile(String)
輕松地模擬方法。

TA貢獻1876條經(jīng)驗 獲得超6個贊
在 jUnit 中,對于像你這樣的場景有一個方便的規(guī)則。
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.
}
添加回答
舉報