[英]Wanted but not invoked mockito test
我想測試以下方法,並驗證
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;
}
我用模仿編寫了以下測試:
@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 () )
問題是什么?
正如大衛·佩雷斯·卡布雷拉(David Perez Cabrera)和前鋒在評論中提到的那樣,您似乎希望您的區塊返回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
等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.