当前位置: 首页>>代码示例>>Java>>正文


Java MockMultipartFile类代码示例

本文整理汇总了Java中org.springframework.mock.web.MockMultipartFile的典型用法代码示例。如果您正苦于以下问题:Java MockMultipartFile类的具体用法?Java MockMultipartFile怎么用?Java MockMultipartFile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


MockMultipartFile类属于org.springframework.mock.web包,在下文中一共展示了MockMultipartFile类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: test_runScript

import org.springframework.mock.web.MockMultipartFile; //导入依赖的package包/类
@Test
public void test_runScript() throws Exception {
    requestAddModule();
    String filename = FilenameUtils.getName(testScriptPath);
    if (filename == null) {
        logger.info("No script found - test escape");
    } else {
        MockMultipartFile file = new MockMultipartFile(
                "file",
                filename,
                "application/sql",
                new FileInputStream(testScriptPath));

        String genericModule = NamingUtils.getContainerName(applicationName, module, "johndoe");

        ResultActions result = mockMvc.perform(
                fileUpload("/module/{moduleName}/run-script", genericModule)
                        .file(file)
                        .session(session)
                        .contentType(MediaType.MULTIPART_FORM_DATA))
                .andDo(print());
        result.andExpect(status().isOk());
    }
}
 
开发者ID:oncecloud,项目名称:devops-cstack,代码行数:25,代码来源:AbstractModuleControllerTestIT.java

示例2: testCreateFromDocuments

import org.springframework.mock.web.MockMultipartFile; //导入依赖的package包/类
@Test
public void testCreateFromDocuments() throws Exception {
    List<MultipartFile> files = Stream.of(
        new MockMultipartFile("files", "filename.txt", "text/plain", "hello".getBytes(StandardCharsets.UTF_8)),
        new MockMultipartFile("files", "filename.txt", "text/plain", "hello2".getBytes(StandardCharsets.UTF_8)))
        .collect(Collectors.toList());

    List<StoredDocument> storedDocuments = files.stream().map(f -> new StoredDocument()).collect(Collectors.toList());

    when(this.auditedStoredDocumentOperationsService.createStoredDocuments(files)).thenReturn(storedDocuments);

    restActions
        .withAuthorizedUser("userId")
        .withAuthorizedService("divorce")
        .postDocuments("/documents", files, Classifications.PUBLIC, null)
        .andExpect(status().isOk());

}
 
开发者ID:hmcts,项目名称:document-management-store-app,代码行数:19,代码来源:StoredDocumentControllerTests.java

示例3: testSaveImageTwice

import org.springframework.mock.web.MockMultipartFile; //导入依赖的package包/类
@Test
public void testSaveImageTwice() throws IOException {
    final SystemUser user = createUserWithPerson();
    final Harvest harvest = model().newHarvest(user.getPerson());

    persistInNewTransaction();

    authenticate(user);

    final long harvestId = harvest.getId();
    final UUID imageId = UUID.randomUUID();

    final byte[] imageData = Files.readAllBytes(new File("frontend/app/assets/images/select2.png").toPath());
    final MultipartFile file = new MockMultipartFile("test.png", "//test/test.png", "image/png", imageData);

    feature.addGameDiaryImageForDiaryEntry(harvestId, GameDiaryEntryType.HARVEST, imageId, file);
    feature.addGameDiaryImageForDiaryEntry(harvestId, GameDiaryEntryType.HARVEST, imageId, file);

    assertNotNull(feature.getGameDiaryImageBytes(imageId, false));
}
 
开发者ID:suomenriistakeskus,项目名称:oma-riista-web,代码行数:21,代码来源:GameDiaryFeatureTest.java

示例4: shouldTryCreateDeviceFirmwareWithInvalidChecksum

import org.springframework.mock.web.MockMultipartFile; //导入依赖的package包/类
@Test
public void shouldTryCreateDeviceFirmwareWithInvalidChecksum() throws Exception {

    when(deviceConfigSetupService.save(org.mockito.Matchers.any(Tenant.class), org.mockito.Matchers.any(Application.class), org.mockito.Matchers.any(DeviceFirmware.class)))
        .thenReturn(ServiceResponseBuilder.<DeviceFirmware>error()
            .withMessage(DeviceFirmwareService.Validations.FIRMWARE_ALREADY_REGISTERED.getCode())
            .withResult(deviceFirmware).build());

    getMockMvc().perform(MockMvcRequestBuilders
            .fileUpload(MessageFormat.format("/{0}/{1}/{2}", application.getName(), BASEPATH, deviceModel.getName()))
            .file(new MockMultipartFile("firmware", "00000".getBytes()))
            .file(new MockMultipartFile("checksum", "00000".getBytes()))
            .param("version", deviceFirmware.getVersion())
            .contentType(MediaType.MULTIPART_FORM_DATA)
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().is4xxClientError())
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(jsonPath("$.code", is(HttpStatus.BAD_REQUEST.value())))
            .andExpect(jsonPath("$.status", is("error")))
            .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
            .andExpect(jsonPath("$.messages[0]", is("Invalid checksum (MD5 or SHA1)")))
            .andExpect(jsonPath("$.result").doesNotExist())
            ;

}
 
开发者ID:KonkerLabs,项目名称:konker-platform,代码行数:26,代码来源:DeviceFirmwareRestControllerTest.java

示例5: testCreateFromDocumentsWithNonWhitelistFile

import org.springframework.mock.web.MockMultipartFile; //导入依赖的package包/类
@Test
public void testCreateFromDocumentsWithNonWhitelistFile() throws Exception {
    List<MultipartFile> files = Stream.of(
        new MockMultipartFile("files", "filename.txt", "text/plain", "hello".getBytes(StandardCharsets.UTF_8)),
        new MockMultipartFile("files", "filename.txt", "", "hello2".getBytes(StandardCharsets.UTF_8)))
        .collect(Collectors.toList());

    List<StoredDocument> storedDocuments = files.stream().map(f -> new StoredDocument()).collect(Collectors.toList());

    when(this.auditedStoredDocumentOperationsService.createStoredDocuments(files)).thenReturn(storedDocuments);

    restActions
        .withAuthorizedUser("userId")
        .withAuthorizedService("divorce")
        .postDocuments("/documents", files, Classifications.PUBLIC, null)
        .andExpect(status().is4xxClientError());
}
 
开发者ID:hmcts,项目名称:document-management-store-app,代码行数:18,代码来源:StoredDocumentControllerTests.java

示例6: testGetBinary

import org.springframework.mock.web.MockMultipartFile; //导入依赖的package包/类
@Test
public void testGetBinary() throws Exception {
    DocumentContentVersion documentContentVersion = new DocumentContentVersion(new StoredDocument(), new MockMultipartFile("files", "filename.txt", "text/plain", "hello".getBytes(StandardCharsets.UTF_8)), null);

    documentContentVersion.setCreatedBy("userId");

    when(documentContentVersionService.findMostRecentDocumentContentVersionByStoredDocumentId(id)).thenReturn(
        documentContentVersion
    );

    restActions
        .withAuthorizedUser("userId")
        .withAuthorizedService("divorce")
        .get("/documents/" + id + "/binary")
        .andExpect(status().isOk());
}
 
开发者ID:hmcts,项目名称:document-management-store-app,代码行数:17,代码来源:StoredDocumentControllerTests.java

示例7: uploadFile

import org.springframework.mock.web.MockMultipartFile; //导入依赖的package包/类
@Test
public void uploadFile() throws Exception {
    // Given
    User user = userRepository.save(User.of("[email protected]", "keesun"));
    assertThat(user).isNotNull();

    this.login(user);

    MockMultipartFile multipartFile = new MockMultipartFile("file", "test.jpg",
        "image/jpeg", "test image content".getBytes());

    String url = "/api/file/";

    // When & Then
    this.mvc.perform(fileUpload(url).file(multipartFile))
        .andDo(print())
        .andDo(document("upload-a-file"))
        .andExpect(status().isOk())
        .andExpect(jsonPath("$.name").value(Matchers.is("test.jpg")))
        .andExpect(jsonPath("$.path").isNotEmpty())
        .andExpect(jsonPath("$.thumbnailPath").isNotEmpty());
}
 
开发者ID:spring-sprout,项目名称:osoon,代码行数:23,代码来源:FileControllerTest.java

示例8: saveOneWithMultipartFile

import org.springframework.mock.web.MockMultipartFile; //导入依赖的package包/类
@Test
public void saveOneWithMultipartFile() {
    Picture picture = pictures.getFirst();

    byte[] file = new byte[1];
    file[0] = ' ';
    MultipartFile multipartFile = new MockMultipartFile(picture.getName(), file);

    service.save(picture, multipartFile);

    assertTrue(picture.equals(service.findOne(picture.getId())));
    Path f = Paths.get(picture.getPath() + picture.getName() + picture.getFileType());
    if (Files.exists(f))
        service.delete(picture);
    else
        fail("the picture wasn't created");
}
 
开发者ID:xSzymo,项目名称:Spring-web-shop-project,代码行数:18,代码来源:PicturesServiceTest.java

示例9: saveOneWithMultipartFileExistNameInDirectory

import org.springframework.mock.web.MockMultipartFile; //导入依赖的package包/类
@Test
public void saveOneWithMultipartFileExistNameInDirectory() {
    Picture picture = pictures.getFirst();
    Picture secondPicture = new Picture(picture.getPath(), picture.getName(), picture.getFileType());

    byte[] file = new byte[1];
    file[0] = ' ';
    MultipartFile multipartFile = new MockMultipartFile(picture.getName(), file);

    service.save(picture, multipartFile);
    service.save(secondPicture, multipartFile);

    assertTrue(picture.equals(service.findOne(picture.getId())));
    assertNull("Error\n(Check your directory, and delete picture with name \"name0\" if exist from last test?)", service.findOne(secondPicture));
    File f = new File(picture.getPath() + picture.getName() + picture.getFileType());
    if (f.exists() && !f.isDirectory())
        service.delete(picture);
    else
        fail("the picture wasn't created");
}
 
开发者ID:xSzymo,项目名称:Spring-web-shop-project,代码行数:21,代码来源:PicturesServiceTest.java

示例10: uploadFile

import org.springframework.mock.web.MockMultipartFile; //导入依赖的package包/类
@Test
public void uploadFile() throws Exception {
    Picture picture = new Picture(ApplicationProperties.PICTURE_PATH, "name", "jpg");
    pictureSaver.deletePicture(picture);

    byte[] file = new byte[1];
    file[0] = ' ';
    MultipartFile multipartFile = new MockMultipartFile(picture.getName(), file);

    pictureSaver.uploadFile(picture, multipartFile);

    Path existPicture = Paths.get(picture.getPath() + picture.getName() + picture.getFileType());
    if (Files.exists(existPicture))
        pictureSaver.deletePicture(picture);
    else
        fail("the picture wasn't created");

    existPicture = Paths.get(picture.getPath() + picture.getName() + picture.getFileType());
    if (Files.exists(existPicture))
        fail("picture still exists");
}
 
开发者ID:xSzymo,项目名称:Spring-web-shop-project,代码行数:22,代码来源:PicturesOperationsTest.java

示例11: failedPutFileWithWrongUuid

import org.springframework.mock.web.MockMultipartFile; //导入依赖的package包/类
@Test
public void failedPutFileWithWrongUuid() throws Exception {
    final long previousRevision = revisionService.getLatest();
    final long previousSize = mediaService.getAll().size();

    final MediaType newMediaType = MediaType.IMAGE;

    final MediaType mediaType = MediaType.IMAGE;
    final MockMultipartFile jsonFile = new MockMultipartFile("file", "texte.jpeg", "sdfsdf", "{json:null}".getBytes());

    formMediaMetadataDto.setMediaType(newMediaType.toString());

    mockMvc.perform(fileUploadAuthenticated("/media/sdpfosdfiosd/file")
            .file(jsonFile)
    )
            .andDo(MockMvcResultHandlers.print())
            .andExpect(status().isNotFound())
            .andReturn();

    Assert.assertEquals(previousSize, mediaService.getAll().size());
    Assert.assertEquals(previousRevision, revisionService.getLatest());
}
 
开发者ID:resourcepool,项目名称:dashboard,代码行数:23,代码来源:MediaControllerMediaWebEditTest.java

示例12: testAddAndDeleteImage

import org.springframework.mock.web.MockMultipartFile; //导入依赖的package包/类
@Test
public void testAddAndDeleteImage() throws IOException {
    final UUID imageId = UUID.randomUUID();
    final byte[] imageData = Files.readAllBytes(new File("frontend/app/assets/images/select2.png").toPath());
    final MultipartFile file = new MockMultipartFile("test.png", "//test/test.png", "image/png", imageData);

    withPerson(person -> {
        final SrvaEvent srvaEvent = model().newSrvaEvent(person);

        onSavedAndAuthenticated(createUser(person), () -> {
            //add
            try {
                mobileSrvaCrudFeature.addImage(srvaEvent.getId(), imageId, file);
                assertEquals(1, gameDiaryImageRepo.findBySrvaEvent(srvaEvent).size());
                assertEquals(imageId, gameDiaryImageRepo.findBySrvaEvent(srvaEvent).get(0).getFileMetadata().getId());
            } catch (IOException e) {
                e.printStackTrace();
                fail();
            }

            //delete
            mobileSrvaCrudFeature.deleteImage(imageId);
            assertEquals(0, gameDiaryImageRepo.findBySrvaEvent(srvaEvent).size());
        });
    });
}
 
开发者ID:suomenriistakeskus,项目名称:oma-riista-web,代码行数:27,代码来源:MobileSrvaCrudFeatureTest.java

示例13: shouldCreateDeviceFirmwareMD5

import org.springframework.mock.web.MockMultipartFile; //导入依赖的package包/类
@Test
public void shouldCreateDeviceFirmwareMD5() throws Exception {

    when(deviceConfigSetupService.save(org.mockito.Matchers.any(Tenant.class), org.mockito.Matchers.any(Application.class), org.mockito.Matchers.any(DeviceFirmware.class)))
        .thenReturn(ServiceResponseBuilder.<DeviceFirmware>ok()
                .withResult(deviceFirmware).build());

    getMockMvc().perform(MockMvcRequestBuilders
            .fileUpload(MessageFormat.format("/{0}/{1}/{2}", application.getName(), BASEPATH, deviceModel.getName()))
            .file(new MockMultipartFile("firmware", "00000".getBytes()))
            .file(new MockMultipartFile("checksum", "dcddb75469b4b4875094e14561e573d8   file.bin".getBytes()))
            .param("version", deviceFirmware.getVersion())
            .contentType(MediaType.MULTIPART_FORM_DATA)
    		.accept(MediaType.APPLICATION_JSON))
            .andExpect(status().is2xxSuccessful())
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(jsonPath("$.code", is(HttpStatus.CREATED.value())))
            .andExpect(jsonPath("$.status", is("success")))
            .andExpect(jsonPath("$.timestamp",greaterThan(1400000000)))
            .andExpect(jsonPath("$.messages").doesNotExist())
            .andExpect(jsonPath("$.result").isMap())
            .andExpect(jsonPath("$.result.version", is(deviceFirmware.getVersion())))
            .andExpect(jsonPath("$.result.uploadTimestamp", notNullValue()))
            ;

}
 
开发者ID:KonkerLabs,项目名称:konker-platform,代码行数:27,代码来源:DeviceFirmwareRestControllerTest.java

示例14: shouldCreateDeviceFirmwareSHA1

import org.springframework.mock.web.MockMultipartFile; //导入依赖的package包/类
@Test
public void shouldCreateDeviceFirmwareSHA1() throws Exception {

    when(deviceConfigSetupService.save(org.mockito.Matchers.any(Tenant.class), org.mockito.Matchers.any(Application.class), org.mockito.Matchers.any(DeviceFirmware.class)))
        .thenReturn(ServiceResponseBuilder.<DeviceFirmware>ok()
                .withResult(deviceFirmware).build());

    getMockMvc().perform(MockMvcRequestBuilders
            .fileUpload(MessageFormat.format("/{0}/{1}/{2}", application.getName(), BASEPATH, deviceModel.getName()))
            .file(new MockMultipartFile("firmware", "00000".getBytes()))
            .file(new MockMultipartFile("checksum", "6934105ad50010b814c933314b1da6841431bc8b".getBytes()))
            .param("version", deviceFirmware.getVersion())
            .contentType(MediaType.MULTIPART_FORM_DATA)
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().is2xxSuccessful())
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(jsonPath("$.code", is(HttpStatus.CREATED.value())))
            .andExpect(jsonPath("$.status", is("success")))
            .andExpect(jsonPath("$.timestamp",greaterThan(1400000000)))
            .andExpect(jsonPath("$.messages").doesNotExist())
            .andExpect(jsonPath("$.result").isMap())
            .andExpect(jsonPath("$.result.version", is(deviceFirmware.getVersion())))
            .andExpect(jsonPath("$.result.uploadTimestamp", notNullValue()))
            ;

}
 
开发者ID:KonkerLabs,项目名称:konker-platform,代码行数:27,代码来源:DeviceFirmwareRestControllerTest.java

示例15: shouldTryCreateDeviceFirmwareWithBadRequest

import org.springframework.mock.web.MockMultipartFile; //导入依赖的package包/类
@Test
public void shouldTryCreateDeviceFirmwareWithBadRequest() throws Exception {

    when(deviceConfigSetupService.save(org.mockito.Matchers.any(Tenant.class), org.mockito.Matchers.any(Application.class), org.mockito.Matchers.any(DeviceFirmware.class)))
        .thenReturn(ServiceResponseBuilder.<DeviceFirmware>error()
            .withMessage(DeviceFirmwareService.Validations.FIRMWARE_ALREADY_REGISTERED.getCode())
            .withResult(deviceFirmware).build());

    getMockMvc().perform(MockMvcRequestBuilders
            .fileUpload(MessageFormat.format("/{0}/{1}/{2}", application.getName(), BASEPATH, deviceModel.getName()))
            .file(new MockMultipartFile("firmware", "00000".getBytes()))
            .file(new MockMultipartFile("checksum", "dcddb75469b4b4875094e14561e573d8".getBytes()))
            .param("version", deviceFirmware.getVersion())
            .contentType(MediaType.MULTIPART_FORM_DATA)
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().is4xxClientError())
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(jsonPath("$.code", is(HttpStatus.BAD_REQUEST.value())))
            .andExpect(jsonPath("$.status", is("error")))
            .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
            .andExpect(jsonPath("$.messages[0]", is("Firmware already registered")))
            .andExpect(jsonPath("$.result").doesNotExist())
            ;

}
 
开发者ID:KonkerLabs,项目名称:konker-platform,代码行数:26,代码来源:DeviceFirmwareRestControllerTest.java


注:本文中的org.springframework.mock.web.MockMultipartFile类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。