用EasyMock能Mock方法内New的对象吗

hw19900825 2017-05-03 09:10:14
现在要做某个方法的Junit测试,异常不好测就想用EasyMock来实现。代码如下
要测的方法
public static boolean createFile(String strFileName, byte[] byteData) {
//这里省略关于文件名的一些正确性的判定
File newfile = new File(strFileName);
try {
FileOutputStream writefile = new FileOutputStream(strFileName);
try {
writefile.write(byteData);
} catch (IOException e1) {
return false;
}
} catch (FileNotFoundException e0) {
return false;
}
return true;
}
测试方法
@Test
public void testCreateFile008() {
String strFileName="//testfile//CreateFile.txt";
byte[] byteDate={0x17,0x18,0x19,0x20,0x21};
FileOutputStream mockFileOutputStream=EasyMock.createMock(FileOutputStream.class);
try{
mockFileOutputStream.write(byteDate);
EasyMock.expectLastCall().andThrow(new IOException());
EasyMock.replay(mockFileOutputStream);
}catch (Exception e){
System.out.print(e.toString());
}
boolean result=FileUtils.createFile(allPath, byteDate);
EasyMock.verify(mockFileOutputStream);
assert(result);
}
想Mock FileOutputStream的write方法抛出异常,但结果Mock的方法始终不执行,是因为这是静态方法吗?还是因为Mock的方法不能替代方法中New的类? 我想要Mock write方法抛出异常完成测试该怎么写啊?
求大神指教
...全文
395 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

50,522

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧