Example usage for org.springframework.mock.web MockMultipartFile MockMultipartFile

List of usage examples for org.springframework.mock.web MockMultipartFile MockMultipartFile

Introduction

In this page you can find the example usage for org.springframework.mock.web MockMultipartFile MockMultipartFile.

Prototype

public MockMultipartFile(String name, @Nullable String originalFilename, @Nullable String contentType,
        InputStream contentStream) throws IOException 

Source Link

Document

Create a new MockMultipartFile with the given content.

Usage

From source file:org.bonitasoft.web.designer.controller.ImportControllerTest.java

@Test
public void should_respond_400_when_file_content_type_is_octetstream_but_filename_is_not_a_zip()
        throws Exception {
    MockMultipartFile file = new MockMultipartFile("file", "myfile.png", "application/octet-stream",
            "foo".getBytes());

    mockMvc.perform(fileUpload("/import/page").file(file)).andExpect(status().isBadRequest())
            .andExpect(jsonPath("type").value("IllegalArgumentException"))
            .andExpect(jsonPath("message").value("Only zip files are allowed when importing a component"));
}

From source file:de.prokimedo.test.IcdTest.java

@Test
public void readVersionIcd() throws Throwable {
    Icd icd = new Icd("123", "diagnose", "type");
    this.service.save(icd);
    File file = new File("src/test/resources/icdTest.csv");
    FileInputStream input = new FileInputStream(file);
    MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain",
            IOUtils.toByteArray(input));

    this.service.saveVersion(multipartFile, "test");
    List<Icd> response = this.service.readVersionIcd("default");
    assertNotEquals(0, response.size());
}

From source file:de.unimannheim.spa.process.rest.ProjectRestControllerTest.java

@Test
public void itShouldCreateAndReturnNewProcessWithFile() throws Exception {
    final String projectIDForTest = createProjectAndReturnID();
    final String processLabelToTest = "newProcessLabelToTest";
    MockMultipartFile processFileToTest = new MockMultipartFile("processFile", "example-spa.bpmn",
            MediaType.MULTIPART_FORM_DATA_VALUE, Files.toByteArray(getFilePath("example-spa.bpmn").toFile()));
    mockMvc.perform(fileUpload("/projects/" + projectIDForTest + "/processes").file(processFileToTest)
            .param("processLabel", processLabelToTest).param("format", "BPMN2")).andExpect(status().isCreated())
            .andExpect(content().contentType(JSON_CONTENT_TYPE))
            .andExpect(jsonPath("$.id", containsString("http://www.uni-mannheim.de/spa/DataBucket/")))
            .andExpect(jsonPath("$.label", equalTo(processLabelToTest)));
}

From source file:org.bonitasoft.web.designer.controller.asset.AssetServiceTest.java

@Test
public void should_upload_a_json_asset() throws Exception {
    Page page = aPage().withId("page-id").build();
    byte[] fileContent = "{ \"some\": \"json\" }".getBytes();
    MockMultipartFile file = new MockMultipartFile("asset.json", "asset.json", "application/javascript",
            fileContent);//from w  w w.j  a  v  a2s .  c  om
    Asset expectedAsset = anAsset().withName("asset.json").withType(AssetType.JSON).withOrder(1).build();

    Asset asset = assetService.upload(file, page, "json");

    verify(assetRepository).save("page-id", asset, fileContent);
    verify(repository).updateLastUpdateAndSave(page);
    assertThat(page.getAssets()).contains(asset);
    assertThat(asset.getId()).isNotNull();
    assertThat(asset).isEqualToIgnoringGivenFields(expectedAsset, "id");
}

From source file:com.trenako.web.controllers.admin.AdminBrandsControllerMappingTests.java

@Test
public void shouldUploadNewBrandImages() throws Exception {
    MockMultipartFile mockFile = new MockMultipartFile("file", "image.jpg", MediaType.IMAGE_JPEG.toString(),
            "file content".getBytes());

    mockMvc()//  ww w.jav  a  2  s. com
            .perform(fileUpload("/admin/brands/upload").file(mockFile).param("entity", "brand").param("slug",
                    ACME))
            .andExpect(status().isOk()).andExpect(flash().attributeCount(1))
            .andExpect(flash().attribute("message", equalTo(AdminBrandsController.BRAND_LOGO_UPLOADED_MSG)))
            .andExpect(redirectedUrl("/admin/brands/acme"));
}

From source file:org.unidle.controller.CreateQuestionControllerTest.java

@Test
public void testQuestionPostWithTagsAndAttachments() throws Exception {
    SecurityContextHolder.getContext()//from  w w w.j a  v a  2  s .  c om
            .setAuthentication(new UsernamePasswordAuthenticationToken(user.getUuid(), null));

    subject.perform(fileUpload("/question/create")
            .file(new MockMultipartFile("attachments", "test.txt", "text/plain",
                    "this is a text file".getBytes()))
            .param("question", "this is a test question").param("tags", "tag1, tag2, tag3"))
            .andExpect(view().name(startsWith("redirect:/question/")));

    assertThat(questionRepository.count()).isEqualTo(1L);
    assertThat(questionRepository.findAll().get(0).getTags()).containsOnly("tag1", "tag2", "tag3");
    assertThat(attachmentRepository.count()).isEqualTo(1L);
}

From source file:org.jtalks.common.web.controller.UserController.java

/**
 * Show edit user profile page for current logged in user.
 *
 * @return edit user profile page/* ww  w .j a  v  a  2 s .  c  o m*/
 * @throws NotFoundException throws if current logged in user was not found
 */
@RequestMapping(value = "/user/edit", method = RequestMethod.GET)
public ModelAndView editProfilePage() throws NotFoundException {
    User user = securityService.getCurrentUser();
    EditUserProfileDto editedUser = new EditUserProfileDto(user);
    editedUser.setAvatar(
            new MockMultipartFile("avatar", "", ImageFormats.JPG.getContentType(), user.getAvatar()));
    return new ModelAndView(EDIT_PROFILE).addObject(EDITED_USER, editedUser);
}

From source file:business.UploadTests.java

@Test(groups = "upload", dependsOnMethods = "createRequest")
public void uploadFileInvalidMimetype() throws IOException {
    UserAuthenticationToken requester = getRequester();
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(requester);

    RequestRepresentation representation = requestController.getRequestById(requester, processInstanceId);
    log.info("Status: " + representation.getStatus());
    int attachmentCount = representation.getAttachments().size();

    ClassLoader classLoader = getClass().getClassLoader();
    URL resource = classLoader.getResource("test/Utrecht_Oude_Gracht_Hamburgerbrug_(LOC).jpg");
    InputStream input = resource.openStream();
    MultipartFile file = new MockMultipartFile(resource.getFile(), resource.getFile().toString(), "undefined",
            input);//from w  ww.ja  va2 s. co  m

    Integer flowTotalChunks = 1;
    Integer flowChunkNumber = 1;
    String flowIdentifier = "flow";

    representation = requestController.uploadRequestAttachment(requester, processInstanceId, resource.getFile(),
            flowTotalChunks, flowChunkNumber, flowIdentifier, file);

    assertEquals(attachmentCount + 1, representation.getAttachments().size());
    printFiles(representation.getAttachments());

    SecurityContextHolder.clearContext();
}

From source file:com.trenako.web.controllers.admin.AdminRailwaysControllerMappingTests.java

@Test
public void shouldUploadNewRailwayImages() throws Exception {
    MockMultipartFile mockFile = new MockMultipartFile("file", "image.jpg", MediaType.IMAGE_JPEG.toString(),
            "file content".getBytes());

    mockMvc()//w w  w . j a v  a2  s.  c o  m
            .perform(fileUpload("/admin/railways/upload").file(mockFile).param("entity", "railway")
                    .param("slug", DB))
            .andExpect(status().isOk()).andExpect(flash().attributeCount(1))
            .andExpect(flash().attribute("message", equalTo(AdminRailwaysController.RAILWAY_LOGO_UPLOADED_MSG)))
            .andExpect(redirectedUrl("/admin/railways/db"));
}

From source file:org.bonitasoft.web.designer.controller.ImportControllerTest.java

@Test
public void should_respond_400_when_file_content_is_empty() throws Exception {
    MockMultipartFile file = new MockMultipartFile("file", "myfile.zip", "application/zip", "".getBytes());

    mockMvc.perform(fileUpload("/import/page").file(file)).andExpect(status().isBadRequest())
            .andExpect(jsonPath("type").value("IllegalArgumentException")).andExpect(jsonPath("message")
                    .value("Part named [file] is needed to successfully import a component"));
}