3 回答

TA贡献1719条经验 获得超6个赞
不依赖于操作系统文件权限,而是使用 PowerMock 模拟 FileUtils.getFile(...) 并使其返回 File 的实例(例如匿名子类),该实例返回 canWrite()/canRead() 的特定值。

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

TA贡献1876条经验 获得超6个赞
在 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.
}
添加回答
举报