### Question:
FileService extends PermissionAwareCrudService<E, D> { @PreAuthorize("isAuthenticated()") public E uploadFile(MultipartFile file) throws Exception { if (file == null) { final String errMsg = "Upload failed. File is null."; logger.error(errMsg); throw new Exception(errMsg); } else if (file.isEmpty()) { final String errMsg = "Upload failed. File is empty."; logger.error(errMsg); throw new Exception(errMsg); } InputStream is = null; byte[] fileByteArray = null; E fileToPersist = getEntityClass().newInstance(); try { is = file.getInputStream(); fileByteArray = IOUtils.toByteArray(is); } catch (Exception e) { throw new Exception("Could not create the bytearray: " + e.getMessage()); } finally { IOUtils.closeQuietly(is); } fileToPersist.setFile(fileByteArray); fileToPersist.setFileType(file.getContentType()); fileToPersist.setFileName(file.getOriginalFilename()); dao.saveOrUpdate(fileToPersist); return fileToPersist; } @SuppressWarnings("unchecked")  FileService(); protected  FileService(Class<E> entityClass); @Override @Autowired @Qualifier("fileDao") void setDao(D dao); @PreAuthorize("isAuthenticated()") E uploadFile(MultipartFile file);  }### Answer:
@Test public void upload_asExpected() throws Exception { byte[] mockupBytes = "Just some mockup bytes".getBytes(); File persistedFile = null; final String fileName = "fileName.txt"; final String fileType = "text/plain"; MockMultipartFile mockMultipartFile = new MockMultipartFile( "fileData", fileName, fileType, mockupBytes); doNothing().when(dao).saveOrUpdate(any(File.class)); persistedFile = crudService.uploadFile(mockMultipartFile); verify(dao, times(1)).saveOrUpdate(any(File.class)); verifyNoMoreInteractions(dao); assertEquals(new String(persistedFile.getFile()), new String(mockupBytes)); assertEquals(persistedFile.getFileName(), fileName); assertEquals(persistedFile.getFileType(), fileType); }
@Test(expected = Exception.class) public void upload_withError() throws Exception { final String fileName = "fileName.txt"; final String fileType = "text/plain"; MockMultipartFile mockMultipartFile = new MockMultipartFile( "fileData", fileName, fileType, (byte[])null); doNothing().when(dao).saveOrUpdate(any(File.class)); crudService.uploadFile(mockMultipartFile); verify(dao, times(1)).saveOrUpdate(any(File.class)); verifyNoMoreInteractions(dao); }
@Test(expected = Exception.class) public void upload_nullFile_shouldThrowException() throws Exception { crudService.uploadFile(null); }
@Test(expected = Exception.class) public void upload_emptyFile_shouldThrowException() throws Exception { byte[] mockupBytes = null; MockMultipartFile emptyFile = new MockMultipartFile("empty", mockupBytes); crudService.uploadFile(emptyFile); }