### Question:
FilePrinter extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fileName = ""; try { fileName = request.getParameter("file"); } catch (Exception e) { e.printStackTrace(); } if (fileName != null && !fileName.equals("")) { String tmpDir = ((File) getServletContext().getAttribute("javax.servlet.context.tempdir")).getAbsolutePath(); File file = new File(tmpDir + "/" + fileName); InputStream inStream = new FileInputStream(file); OutputStream outStream = response.getOutputStream(); BufferedInputStream bis = new BufferedInputStream(inStream); int bufSize = 1024 * 8; byte[] bytes = new byte[bufSize]; int count = bis.read(bytes); while (count != -1 && count <= bufSize) { outStream.write(bytes, 0, count); count = bis.read(bytes); } if (count != -1) outStream.write(bytes, 0, count); outStream.close(); } } FilePrinter(); void init(ServletConfig config);  }### Answer:
@Test public void testDoGet() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); ServletConfig config = mock(ServletConfig.class); ServletContext context = mock(ServletContext.class); RequestDispatcher dispatcher = mock(RequestDispatcher.class); ServletOutputStream stream = mock(ServletOutputStream.class); when(config.getServletContext()).thenReturn(context); when(context.getRequestDispatcher("/interface.jsp")).thenReturn(dispatcher); when(request.getParameter("file")).thenReturn("prueba.txt"); URL url = this.getClass().getResource("/prueba.txt"); File testFile = new File(url.getFile()); when(context.getAttribute("javax.servlet.context.tempdir")).thenReturn(new File(testFile.getParent())); when(response.getOutputStream()).thenReturn(stream); FilePrinter file = new FilePrinter(); try { file.init(config); file.doGet(request, response); } catch (ServletException ex) { fail("Should not raise exception " + ex.toString()); } catch (IOException ex) { fail("Should not raise exception " + ex.toString()); } }
@Test public void testDoGetFail() throws Exception { HttpServletRequest request = null; HttpServletResponse response = null; FilePrinter instance = new FilePrinter(); instance.doGet(request, response); }