Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save criminy/1097252 to your computer and use it in GitHub Desktop.
Save criminy/1097252 to your computer and use it in GitHub Desktop.
Abstract Unit test for a @controller with MultipartHttpServletRequest
import static org.mockito.Mockito.*;
/**
* Boostraps a MultipartHttpServletRequest using mockito.
* To add a request parameter, define a method called 'parameterName', where request attribute is 'name'.
* To add a multipart file, define a method called 'fileName', where the multipart file is called 'name'.
* Class is very limited but works as it should providing you use a specific subset of the methods on {@link MultipartHttpServletRequest}.
* Subset:
* MultipartHttpServletRequest.getParameter
* MultipartHttpServletRequest.getFileMap
* Map.*
* MultipartFile.getInputStream
*/
public abstract class AbstractMockitoMultipartHttpServletRequestUnitTest {
protected MultipartHttpServletRequest request;
Logger log = Logger.getLogger(AbstractMockitoMultipartHttpServletRequestUnitTest.class);
public MultipartHttpServletRequest getRequest() {
return request;
}
protected String beanName(String name,String prefix)
{
return name.substring(prefix.length()).substring(0,1).toLowerCase() +
name.substring(prefix.length()+1);
}
@Before
public void setupTest() throws Exception
{
request = mock(MultipartHttpServletRequest.class);
Map<String,MultipartFile> fileMap = new HashMap<String, MultipartFile>();
when(request.getFileMap()).thenReturn(fileMap);
for(Method m : this.getClass().getMethods())
{
if(m.getName().startsWith("parameter"))
{
String ret = (String) m.invoke(this);
String name = beanName(m.getName(),"parameter");
log.debug("found parameter " + name + " == " + ret);
when(request.getParameter(name)).thenReturn(ret);
}
if(m.getName().startsWith("file"))
{
String name = beanName(m.getName(),"file");
log.debug("found file " + name);
MultipartFile file = mock(MultipartFile.class);
when(file.getInputStream()).thenReturn((InputStream) m.invoke(this));
fileMap.put(name,file);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment