Created
July 21, 2011 14:02
-
-
Save criminy/1097252 to your computer and use it in GitHub Desktop.
Abstract Unit test for a @controller with MultipartHttpServletRequest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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