mercredi 4 mars 2015

Mocking apache-commons file upload with Mockito - build request manually

I'm trying unit test a servlet processing a xml file with the following code below and could use some direction on building the request manually :



@Test
public void testFacadeLADServlet() throws Exception {

HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);

File file = new File("src/test/resources/LAD_PREMIA_PLUS_2050.xml");
FileInputStream in = new FileInputStream(file);
ServletInputStream srvInputStream = new MockServletInputStream(in);

when(request.getContentType()).thenReturn("multipart/form-data; boundary=BbC04y7F7VsZ5f6");
when(request.getCharacterEncoding()).thenReturn("UTF-8");
when(request.getContentLength()).thenReturn(13312);
when(request.getInputStream()).thenReturn(srvInputStream);

PrintWriter writer = new PrintWriter("C:\\TEMP\\somefile.txt");
when(response.getWriter()).thenReturn(writer);

servlet.init(null);
servlet.doPost(request, response);
}


MockServletInputStream is a wrapper class :



class MockServletInputStream extends ServletInputStream {

private final InputStream sourceStream;

public MockServletInputStream(InputStream sourceStream){
Assert.assertNotNull("L'inputStream ne peut être null", sourceStream);
this.sourceStream = sourceStream;
}

@Override
public int read() throws IOException {
return this.sourceStream.read();
}

@Override
public void close() throws IOException {
super.close();
this.sourceStream.close();
}
}


In the servlet :



ServletFileUpload fileUpload = new ServletFileUpload(defaultFileItem);
fileUpload.setSizeMax(MAXSIZE);
List<?> list = fileUpload.parseRequest(request);


The fileUpload.parseRequest(request) always returns an empty list.


Aucun commentaire:

Enregistrer un commentaire