java - 模拟 (file.exists() && file.isDirectory() java
问题描述
我有一个检查文件存在的java方法..
public String checkFileExistance(String arg) throws IOException {
String FolderPath = SomePath
File file = new File(FolderPath);
if (file.exists() && file.isDirectory()) {
//Do something here
}
}
我想模拟 file.exist() 和 file.isDirectory() 让它总是返回true
我尝试了以下方法:
public void test_checkFileExistance1() throws IOException {
/**Mock*/
File mockedFile = Mockito.mock(File.class);
Mockito.when(mockedFile.exists()).thenReturn(true);
Mockito.when(mockedFile.isDirectory()).thenReturn(true);
/**Actual Call*/
ProcessClass.checkFileExistance("arg");
}
但它总是返回false
解决方案
您模拟 a File
,但这不是您班级中使用的。在你的类中,你调用new File(...)
它返回一个真实的 File
Object
; 不是你准备的那个。
您可以使用 PowerMockito 来执行此操作。
类似于以下内容:
@RunWith(PowerMockRunner.class)
@PrepareForTest(TheClassWithTheCheckFileExistanceMethod.class)
public class TheTest {
@Before
public void setup() {
final File mockFile = mock(File.class);
Mockito.doReturn(true).when(mockFile).exists();
// Whatever other mockery you need.
PowerMockito.whenNew(File.class).withAnyArguments()
.thenReturn(mockFile);
}
}
会这样做。
推荐阅读
- node.js - 使用带有 nodejs 的 vega 的画布问题(仅限服务器端)
- python - 在 Pandas DataFrame 中填充 FRED 数据中的漏洞
- c++ - 琐碎对象和非琐碎对象有什么区别
- excel - 向组合框添加多个范围
- ruby-on-rails - 尝试解码 JWT 令牌,但无法访问返回意外对象和属性的解码函数
- bioinformatics - 删除过度代表序列时出错:TypeError:强制转换为 Unicode:需要字符串或缓冲区,找到 NoneType
- android - 在Android服务器端的应用购买验证中寻找订阅平台
- c++ - 'void visualizar()' 的新声明含糊不清
- python - 正确更新 matplotlib 图 - tkinter
- javascript - 根据 div 高度拆分溢出文本