Spring MockMvc不适用于ModelAttribute中的MultipartFile

时间:2018-02-19 05:34:49

标签: spring testing file-upload multipart mockmvc

我正在尝试对我的图像上传操作应用单元测试,但是当我尝试运行测试时,ImageFileModel的MultipartFile不会注入控制器。

这是我的ImageFileModel:

move_uploaded_file($_FILES['image']['tmp_name'], "/upload/".$imageName.".jpg");

这是My ImageController类:

public class ImageFileModel {

    private Long id;
    private MultipartFile file;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public MultipartFile getFile() {
        return file;
    }

    public void setFile(MultipartFile file) {
        this.file = file;
    }

}

这是我的ImageControllerTest类:

@Controller
public class ImageController {

    private final ImageService imageService;


    public ImageController(ImageService imageService) {
        this.imageService = imageService;

    }


    @PostMapping("motorcycle/{id}/image")
    public String handleImagePost(@PathVariable String id, @ModelAttribute ImageFileModel fileModel, BindingResult bindingResult){

        new ImageValidator().validate(fileModel,bindingResult);

        if(bindingResult.hasErrors()){
            System.out.println("DEBUG INFO ::::::::::::::: inside error condition for this id : " + id);
            return "motorcycle/imageuploadform";
        }

        imageService.saveImageFile(Long.valueOf(id),fileModel.getFile());

        return "redirect:/motorcycle/" + id + "/show/";

    }

}

我得到的错误是:

public class ImageControllerTest {

    @Mock
    ImageService imageService;

    @Mock
    MotorcycleService motorcycleService;

    ImageController controller;

    MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);

        controller = new ImageController(imageService,motorcycleService);
        mockMvc = MockMvcBuilders.standaloneSetup(controller)
                .setControllerAdvice(new ControllerExceptionHandler())
                .build();
    }

    @Test
    public void handleImagePost() throws Exception {
        //GIVEN
        MockMultipartFile multipartFile =
                new MockMultipartFile("imagefile", "image.jpg", "text/plain",
                        "image byte data..".getBytes());


        //WHEN & THEN
        mockMvc.perform(MockMvcRequestBuilders.fileUpload("/motorcycle/1/image")
                .file(multipartFile)
                .param("id", "2"))

                .andExpect(status().is3xxRedirection())
                .andExpect(header().string("Location", "/motorcycle/1/show/"));

        verify(imageService, times(1)).saveImageFile(anyLong(), any());
    }

}

我在调试模式下运行测试然后我看到在控制器上传递的ImageFileModel中的id值,但文件(MultiPartFile)没有通过。 我怎么解决这个问题?

0 个答案:

没有答案