我想测试以下方法,并验证
fi.write( file ) ;
被执行。
@RequestMapping(value="UploadServlet", method=RequestMethod.POST)
public String uploadfile(HttpServletRequest request, HttpServletResponse response, HttpSession session ) throws IOException{
filePath = "C:\\JavaWorkspace\\justbuyit\\src\\main\\webapp\\resources\\images\\";
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(largefile);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fileName = fi.getName();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
session.setAttribute("filepath","resources/images/"+fileName.substring(fileName.lastIndexOf("\\")+1) );
fi.write( file ) ;
request.setAttribute("filewritten", true);
request.setAttribute("filename", fileName.substring(fileName.lastIndexOf("\\")+1));
}
}
}catch(Exception ex) {
System.out.println(ex);
}
return "addProduct";
}
public void setFactory(DiskFileItemFactory factory) {
this.factory = factory;
}
public void setUpload(ServletFileUpload upload) {
this.upload = upload;
}
我在mockito中写了以下测试:
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
uController = new UploadController();
}
@Test
public void testWriteCommandGetsExecutes() throws Exception{
uController.setFactory(factory);
uController.setUpload(upload);
when(i.hasNext()).thenReturn(false);
when((FileItem)i.next()).thenReturn(fi);
when(fi.isFormField()).thenReturn(false);
uController.uploadfile(request, response, session);
verify(fi).write(file);
}}
然而我收到错误
wanted but not invoked: fi.write( file )
在我的报道中,这一行显示为黄色:
while ( i.hasNext () )
有什么问题?
答案 0 :(得分:1)
在评论中提到的David Perez Cabrera和striker,看起来您希望您的块返回true然后返回false。 Mockito为此支持几种语法选择,因此其中任何一种都应该有效:
when(i.hasNext()).thenReturn(true, false);
或
when(i.hasNext()).thenReturn(true).thenReturn(false);
为了将来参考,Mockito的行为是按顺序执行操作,然后永远重复最后一个操作,这意味着对上面存根的hasNext
的调用将返回true
,false
, false
,false
等等,而不是true
,false
,true
,false
,true
等等。