List of usage examples for org.springframework.mock.web MockMultipartFile MockMultipartFile
public MockMultipartFile(String name, @Nullable String originalFilename, @Nullable String contentType, InputStream contentStream) throws IOException
From source file:org.jtalks.common.web.controller.UserControllerTest.java
@Test public void testEditProfileWithAvatarValidationFailed() throws Exception { User user = mock(User.class); when(user.getAvatar()).thenReturn(new byte[0]); when(securityService.getCurrentUser()).thenReturn(user); EditUserProfileDto userDto = mock(EditUserProfileDto.class); when(userDto.getAvatar()).thenReturn( new MockMultipartFile("avatar", "", ImageFormats.JPG.getContentType(), new byte[] { 1 })); BindingResult bindingResult = mock(BindingResult.class); when(bindingResult.hasErrors()).thenReturn(true); when(bindingResult.hasFieldErrors("avatar")).thenReturn(true); ModelAndView mav = controller.editProfile(userDto, bindingResult); assertViewName(mav, "editProfile"); verify(userDto).setAvatar(any(MultipartFile.class)); verify(userService, never()).editUserProfile(any(String.class), any(String.class), any(String.class), any(String.class), any(String.class), Matchers.<byte[]>any()); }
From source file:fragment.web.ChannelControllerTest.java
@Test public void testEditValidCatalogImage() throws Exception { Channel existingChannel = channelDAO.find("3"); ChannelLogoForm form = new ChannelLogoForm(existingChannel); MultipartFile logo = new MockMultipartFile("channelLogo.jpeg", "channelLogo.jpeg", "byte", "ChannelLogo".getBytes()); form.setLogo(logo);/*from w w w .ja v a 2 s .c om*/ BindingResult result = validate(form); String result1 = channelController.editChannelLogo(form, result, request, map); System.out.println(result1); Assert.assertTrue(result1.contains(existingChannel.getId().toString())); }
From source file:org.dawnsci.marketplace.server.MarketplaceServerTest.java
/** * Tests that a user that is signing in can upload a new solution including * the p2-repository, screenshot and image. *//* w w w . j a v a 2s.co m*/ @Test @Sql("/system-test-data.sql") // creates user entry in the database public void testRestPostSolution() throws Exception { // sign in and upload a new solution SolutionUploadSession session = signInAndUploadSolution(); InputStream is = MarketplaceServerTest.class.getClassLoader().getResource("data/p2-repo.zip").openStream(); MockMultipartFile file = new MockMultipartFile("file", "p2-repo.zip", "multipart/form-data", is); // update the newly created solution with files // TODO: Move to separate test String body2 = this.mocMvc.perform(fileUpload("/upload-p2repo").file(file) // upload the p2-repository .param("id", session.node.getId().toString()).with(csrf()).session((MockHttpSession) session.http)) .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); Node node2 = loadSerializedNode(body2); // verify that we have the correct update site URL assertEquals("/files/" + node2.getId() + "/", node2.getUpdateurl()); // download the p2-repository index files this.mocMvc.perform(get("http://localhost:8080/files/" + node2.getId() + "/artifacts.jar")) .andExpect(status().isOk()); this.mocMvc.perform(get("http://localhost:8080/files/" + node2.getId() + "/content.jar")) .andExpect(status().isOk()); ResponseEntity<String> entity = this.restTemplate .getForEntity("http://localhost:" + this.port + "/mpc/content/1/api/p", String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); Marketplace m = loadSerializedMarketplace(entity.getBody()); assertEquals(Long.valueOf(1), m.getNode().getId()); // sign out this.mocMvc.perform(post("http://localhost:8080/signout").with(csrf())) .andExpect(status().is3xxRedirection()); }
From source file:org.bonitasoft.web.designer.controller.ImportControllerTest.java
@Test public void should_force_a_widget_import() throws Exception { //We construct a mockfile (the first arg is the name of the property expected in the controller MockMultipartFile file = new MockMultipartFile("file", "myfile.zip", "application/zip", "foo".getBytes()); ImportReport expectedReport = anImportReportFor(aWidget().id("aWidget").name("myWidgetName")).build(); when(pathImporter.forceImportFromPath(unzipedPath, widgetImporter)).thenReturn(expectedReport); mockMvc.perform(fileUpload("/import/widget?force=true").file(file)) .andExpect(content().contentType(MediaType.TEXT_PLAIN)).andExpect(status().isCreated()) .andExpect(jsonPath("element.id").value("aWidget")) .andExpect(jsonPath("element.name").value("myWidgetName")); }
From source file:com.github.cherimojava.orchidae.controller._PictureController.java
private ResultActions createPicture(String name, String type) throws Exception { try (InputStream s = new ClassPathResource("gradient.png").getInputStream();) { byte[] bytes = StreamUtils.copyToByteArray(s); MockMultipartFile file = new MockMultipartFile(name, name + "." + type, "image/" + type, bytes); return mvc .perform(fileUpload("/picture").file(file).accept(MediaType.APPLICATION_JSON).session(session)) .andExpect(status().isCreated()).andExpect(content().contentType(MediaType.APPLICATION_JSON)); }// w w w . j a v a 2 s . co m }
From source file:org.shareok.data.documentProcessor.DocumentProcessorUtil.java
public static MultipartFile getMultiPartFileFromFilePath(String filePath, String contentType) { MultipartFile multipartFile = null;/*from ww w . j a v a2 s. c o m*/ try { File file = new File(filePath); FileInputStream input = new FileInputStream(file); multipartFile = new MockMultipartFile("file", file.getName(), contentType, IOUtils.toByteArray(input)); } catch (IOException ioex) { logger.error("Cannot get the multipart file form " + filePath, ioex); } return multipartFile; }
From source file:fragment.web.ChannelControllerTest.java
@Test public void testEditInvalidChannelImage() throws Exception { Channel existingChannel = channelDAO.find("3"); ChannelLogoForm form = new ChannelLogoForm(existingChannel); MultipartFile logo = new MockMultipartFile("veer.jee", "veer.jee", "bytes", "veer.jee".getBytes()); form.setLogo(logo);//from www.java 2 s . c o m BindingResult result = validate(form); String result1 = channelController.editChannelLogo(form, result, request, map); Assert.assertNotNull(result1); Assert.assertEquals("{\"errormessage\":\"File should have either .jpeg/.jpg/.png/.gif/.bmp extension\"}", result1); }
From source file:au.com.gaiaresources.bdrs.controller.test.TestDataCreator.java
public void createTaxonGroups(int count, int rand, boolean createAttributes) throws Exception { if (rand > 0) { count = count + (random.nextBoolean() ? random.nextInt(rand) : -random.nextInt(rand)); }/*from w w w .j av a 2 s . co m*/ log.info(String.format("Creating %d Taxon Groups", count)); // Look for the directory of images, if found we will use that // otherwise we will use a generated set of images. byte[] defaultThumbnail = createImage(250, 140, "Test Taxon Group Thumb"); byte[] defaultImage = createImage(640, 480, "Test Taxon Group Image"); Map<String, byte[]> defaultImageMap = new HashMap<String, byte[]>(); defaultImageMap.put("image", defaultImage); defaultImageMap.put("thumbNail", defaultThumbnail); Preference testDataDirPref = prefDAO.getPreferenceByKey(TEST_DATA_IMAGE_DIR); MockMultipartHttpServletRequest request; MockHttpServletResponse response; for (int i = 0; i < count; i++) { request = new MockMultipartHttpServletRequest(); response = new MockHttpServletResponse(); request.setMethod("POST"); request.setRequestURI("/bdrs/admin/taxongroup/edit.htm"); request.setParameter("name", TEST_GROUPS[random.nextInt(TEST_GROUPS.length)]); request.setParameter("behaviourIncluded", String.valueOf(random.nextBoolean())); request.setParameter("firstAppearanceIncluded", String.valueOf(random.nextBoolean())); request.setParameter("lastAppearanceIncluded", String.valueOf(random.nextBoolean())); request.setParameter("habitatIncluded", String.valueOf(random.nextBoolean())); request.setParameter("weatherIncluded", String.valueOf(random.nextBoolean())); request.setParameter("numberIncluded", String.valueOf(random.nextBoolean())); // Image and Thumbnail for (String propertyName : new String[] { "image", "thumbNail" }) { String key = String.format("%s_file", propertyName); String image_filename = String.format("%s_filename.png", propertyName); byte[] imageData = getRandomImage(testDataDirPref, 250, 140); imageData = imageData == null ? defaultImageMap.get(propertyName) : imageData; MockMultipartFile mockImageFile = new MockMultipartFile(key, image_filename, "image/png", imageData); ((MockMultipartHttpServletRequest) request).addFile(mockImageFile); request.setParameter(propertyName, image_filename); } // Attributes if (createAttributes) { int curWeight = 0; String attributeOptions = "Option A, Option B, Option C, Option D"; String rangeIntOptions = "0, 50"; int index = 0; for (Boolean isTag : new Boolean[] { true, false }) { for (AttributeType attrType : AttributeType.values()) { request.addParameter("add_attribute", String.valueOf(index)); request.setParameter(String.format("add_weight_%d", index), String.valueOf(curWeight)); request.setParameter(String.format("add_name_%d", index), String.format("%s name%s", attrType.getName(), isTag ? " Tag" : "")); request.setParameter(String.format("add_description_%d", index), String.format("%s description%s", attrType.getName(), isTag ? " Tag" : "")); request.setParameter(String.format("add_typeCode_%d", index), attrType.getCode()); request.setParameter(String.format("add_tag_%d", index), isTag.toString().toLowerCase()); //request.setParameter(String.format("add_scope_%d", index), scope.toString()); if (AttributeType.STRING_WITH_VALID_VALUES.equals(attrType)) { request.setParameter(String.format("add_option_%d", index), attributeOptions); } else if (AttributeType.INTEGER_WITH_RANGE.equals(attrType)) { request.setParameter(String.format("add_option_%d", index), rangeIntOptions); } index = index + 1; curWeight = curWeight + 100; } } } handle(request, response); } }
From source file:com.trenako.web.controllers.admin.AdminBrandsControllerTests.java
private static MultipartFile buildFile(MediaType mediaType) { byte[] content = "file content".getBytes(); return new MockMultipartFile("image.jpg", "image.jpg", mediaType.toString(), content); }
From source file:org.dawnsci.marketplace.server.MarketplaceServerTest.java
@Test @Sql("/system-test-data.sql") // creates user entry in the database public void testRestUploadScreenshot() throws Exception { // sign in and upload a new solution SolutionUploadSession session = signInAndUploadSolution(); MockMultipartFile screenshot = new MockMultipartFile("file", "screenshot.png", "multipart/form-data", MarketplaceServerTest.class.getClassLoader().getResource("data/screenshot.png").openStream()); // upload the screenshot String body = this.mocMvc.perform(fileUpload("/upload-screenshot").file(screenshot) // upload the p2-repository .param("id", session.node.getId().toString()).with(csrf()).session((MockHttpSession) session.http)) .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); Node node = loadSerializedNode(body); // verify that we have the correct screenshot file name assertEquals("screenshot.png", node.getScreenshot()); // then try to download the screenshot file this.mocMvc.perform(get("http://localhost:8080/files/" + node.getId() + "/" + node.getScreenshot())) .andExpect(status().isOk()); // sign out//from w w w.j av a 2 s . co m this.mocMvc.perform(post("http://localhost:8080/signout").with(csrf())) .andExpect(status().is3xxRedirection()); }