StaticResourceServlet extends HttpServlet { @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final File requestedFile = getRequestedFile(req); if (!requestedFile.exists() || !requestedFile.isFile()) { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } final String etag = getEtag(requestedFile); if (etag.equals(req.getHeader("If-None-Match"))) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } final File compressedStatic = getCompressedVersion(requestedFile); InputStream fileContent = null; try { resp.setContentType(getContentType(requestedFile.getName())); resp.setHeader("ETag", etag); resp.setStatus(HttpServletResponse.SC_OK); if (isClientCompressionSupported(req) && compressedStatic.exists()) { resp.setHeader("Content-Encoding", "gzip"); resp.setContentLength((int) compressedStatic.length()); fileContent = new FileInputStream(compressedStatic); } else { resp.setContentLength((int) requestedFile.length()); fileContent = new FileInputStream(requestedFile); } IOUtils.copy(fileContent, resp.getOutputStream()); } finally { IOUtils.closeQuietly(fileContent); } }    }
@Test public void testNoSuchFile() throws ServletException, IOException { final StaticResourceServlet servlet = Mockito .mock(StaticResourceServlet.class); Mockito.doCallRealMethod() .when(servlet) .doGet(Matchers.any(HttpServletRequest.class), Matchers.any(HttpServletResponse.class)); final ServletContext servletContext = Mockito .mock(ServletContext.class); Mockito.when(servletContext.getRealPath("notexisting.css")).thenReturn( new File(rootDirectory, "notexisting.css").getAbsolutePath()); Mockito.when(servlet.getServletContext()).thenReturn(servletContext); final HttpServletRequest request = Mockito .mock(HttpServletRequest.class); Mockito.when(request.getServletPath()).thenReturn("notexisting.css"); final HttpServletResponse response = Mockito .mock(HttpServletResponse.class); servlet.doGet(request, response); Mockito.verify(response).setStatus(HttpServletResponse.SC_NOT_FOUND); }