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:de.tobiasbruns.content.storage.ContentControllerITCase.java

@Test
public void test12_uploadNewBinaryFile() throws Exception {
    InputStream testStream = TestUtils.loadFile("requests/testimg.jpeg");
    MockMultipartFile mockFile = new MockMultipartFile("file", "testimage.jpeg", "image/jpeg", testStream);

    MockMultipartHttpServletRequestBuilder builder = MockMvcRequestBuilders
            .fileUpload(BASE + "/folder/testimage.jpeg");
    builder.with(new RequestPostProcessor() {
        @Override//  w w w.j  a  va  2 s  .c o  m
        public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
            request.setMethod("PUT");
            return request;
        }
    });

    mockMvc.perform(builder.file(mockFile)).andExpect(status().is2xxSuccessful());
}

From source file:org.openmrs.module.radiology.test.RadiologyTestData.java

/**
 * Convenience method constructing an empty multipart file for the tests
 *//*from   ww  w. j  a  v a  2 s . c  om*/
public static MockMultipartFile getEmptyMockMultipartFileForMockObsWithComplexConcept() {
    final String fileName = "test.jpg";
    final byte[] content = "".getBytes();
    return new MockMultipartFile("complexDataFile", fileName, "image/jpeg", content);
}

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

private String createProcessAndReturnID(String projectID, String format) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    String processCreatedID = "";
    final String processLabel = "newProcessLabelToTest";
    MockMultipartFile processFile = new MockMultipartFile("processFile", "example-spa.bpmn",
            MediaType.APPLICATION_OCTET_STREAM_VALUE,
            Files.toByteArray(getFilePath("example-spa.bpmn").toFile()));
    String JSONFromServer = mockMvc
            .perform(fileUpload("/projects/" + projectID + "/processes").file(processFile)
                    .param("processLabel", processLabel).param("format", format))
            .andReturn().getResponse().getContentAsString();
    try {//from ww  w.ja v a2s .c o  m
        Map<String, Object> map = mapper.readValue(JSONFromServer, new TypeReference<Map<String, Object>>() {
        });
        processCreatedID = ((String) map.get("id")).substring(42);
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return processCreatedID;
}

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

@Test
public void should_respond_an_error_with_ok_code_when_import_exception_occurs_while_importing_a_page()
        throws Exception {
    MockMultipartFile file = new MockMultipartFile("file", "myfile.zip", "application/zip", "foo".getBytes());
    when(pathImporter.importFromPath(unzipedPath, pageImporter))
            .thenThrow(new ImportException(Type.SERVER_ERROR, "an error messge"));

    mockMvc.perform(fileUpload("/import/page").file(file))
            .andExpect(content().contentType(MediaType.TEXT_PLAIN)).andExpect(status().isAccepted())
            .andExpect(jsonPath("type").value("SERVER_ERROR"))
            .andExpect(jsonPath("message").value("an error messge"));
}

From source file:com.github.cherimojava.orchidae.controller._PictureController.java

@Test
public void batchingWorking() throws Exception {
    String batchId = "0123456789abcdef";
    try (InputStream s = new ClassPathResource("gradient.png").getInputStream();) {

        byte[] bytes = StreamUtils.copyToByteArray(s);
        MockMultipartFile file = new MockMultipartFile("b", "b.png", "image/png", bytes);
        mvc.perform(fileUpload("/picture").file(file).accept(MediaType.APPLICATION_JSON).session(session)
                .param(PictureController.BATCH_IDENTIFIER, batchId)).andExpect(status().isCreated())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON));

        file = new MockMultipartFile("c", "c.png", "image/png", bytes);
        mvc.perform(fileUpload("/picture").file(file).accept(MediaType.APPLICATION_JSON).session(session)
                .param(PictureController.BATCH_IDENTIFIER, batchId)).andExpect(status().isCreated())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON));
    }//from  w ww.j a  v a  2s .  com
    getLatest(10).andExpect(jsonPath("$[0].title", is("b")))
            .andExpect(jsonPath("$[0].batchUpload", is(batchId)))
            .andExpect(jsonPath("$[0].originalName", is("b.png"))).andExpect(jsonPath("$[1].title", is("c")))
            .andExpect(jsonPath("$[1].batchUpload", is(batchId)))
            .andExpect(jsonPath("$[1].originalName", is("c.png")));
    assertEquals(2, factory.load(BatchUpload.class, batchId).getPictures().size());
}

From source file:cn.org.once.cstack.explorer.FileControllerTestIT.java

private ResultActions upload(File localFile, String remotePath) throws Exception {
    String container = applicationName + "-johndoe";
    String url = "/file/container/" + container + "/application/" + applicationName + "?path=" + remotePath;
    MockMultipartFile mockMultipartFile = new MockMultipartFile("file", localFile.getName(),
            "multipart/form-data", new FileInputStream(localFile));
    return mockMvc.perform(MockMvcRequestBuilders.fileUpload(url).file(mockMultipartFile).session(session)
            .contentType(MediaType.MULTIPART_FORM_DATA)).andDo(print());
}

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

@Test
public void testEditProfileWithNullAvatar() 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())//from  www .  ja v a  2s .com
            .thenReturn(new MockMultipartFile("avatar", "", ImageFormats.JPG.getContentType(), new byte[0]));
    BindingResult bindingResult = mock(BindingResult.class);
    when(bindingResult.hasErrors()).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:fr.treeptik.cloudunit.explorer.FileControllerTestIT.java

private ResultActions upload(File localFile, String remotePath) throws Exception {
    String container = "int-johndoe-" + applicationName + "-tomcat-8";
    String url = "/file/container/" + container + "/application/" + applicationName + "?path=" + remotePath;
    MockMultipartFile mockMultipartFile = new MockMultipartFile("file", localFile.getName(),
            "multipart/form-data", new FileInputStream(localFile));
    return mockMvc.perform(MockMvcRequestBuilders.fileUpload(url).file(mockMultipartFile).session(session)
            .contentType(MediaType.MULTIPART_FORM_DATA)).andDo(print());
}

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

@Test
public void should_import_a_widget() 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.importFromPath(unzipedPath, widgetImporter)).thenReturn(expectedReport);

    mockMvc.perform(fileUpload("/import/widget").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:org.shareok.data.sagedata.SageSourceDataHandlerImpl.java

@Override
public String getDspaceLoadingData(String filePath) {
    MultipartFile multipartFile = null;//from ww w  .j  av a  2s  .  co m
    try {
        File file = new File(filePath);
        FileInputStream input = new FileInputStream(file);
        multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input));
    } catch (IOException ioex) {
        Logger.getLogger(SageSourceDataHandlerImpl.class.getName()).log(Level.SEVERE, null, ioex);
    }
    return getDspaceLoadingData(multipartFile);
}