gpt4 book ai didi

java - 想要但没有调用mockito测试

转载 作者:行者123 更新时间:2023-12-01 11:23:06 25 4
gpt4 key购买 nike

我想测试以下方法,并验证

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 () ) 

问题是什么?

最佳答案

David Perez Cabrerastriker评论中提到,您似乎希望您的 block 返回 true,然后返回 false。 Mockito 支持多种语法选择,因此其中任何一个都应该有效:

when(i.hasNext()).thenReturn(true, false);

when(i.hasNext()).thenReturn(true).thenReturn(false);

供将来引用,Mockito 的行为是按顺序执行操作,然后永远重复最后一个操作,这意味着对上面 stub 的 hasNext 的调用将返回 truefalsefalsefalse 等,而不是 truefalsetruefalsetrue 等等。

关于java - 想要但没有调用mockito测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31033160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com