Spring Boot - 使用MockMvc测试MultiPartFile图像上传RestController的JUnit错误

时间:2017-09-18 02:42:57

标签: spring spring-mvc spring-boot junit spring-test

我正在尝试测试上传图片的控制器类。端点接收长Id和MultipartFile文件。控制器的代码是:

@PostMapping(value = "/{userId}/image")
@ResponseStatus(HttpStatus.OK)
public UserDto uploadProfileImage(@PathVariable Long userId, @RequestParam("image")  MultipartFile image) throws EntityNotFoundException {
    User user =  imageService.uploadImage(userId,image);
    return UserMapper.makeDto(user);
}

测试是:

@Test
public void whenUploadingImageThenReturnTheUser()throws Exception{

    MockMultipartFile uploadFile = new MockMultipartFile("uploadFile", new byte[1]);
    User user = new User("email@mail.com","pass", "name","lastNmae","description","123123",null);

    when(imageService.uploadImage(1L,uploadFile)).thenReturn(user);

    MvcResult result = mockMvc.perform(MockMvcRequestBuilders.fileUpload("/v1/users/"+1L+"/image").file(uploadFile).accept(contentType)).andExpect(status().isOk()).andReturn();

    String content = result.getResponse().getContentAsString();

    UserDto userDto =asObject(content);
    assertEquals(userDto.getFirstName(),user.getFirstName());
}

当我运行测试时,控制台会显示:

java.lang.AssertionError: Status 
Expected :200
Actual   :400

at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:665)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at com.empresa.mascotar.userService.controllers.UserControllerTest.whenUploadingImageThenReturnTheUser(UserControllerTest.java:165)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)

我不知道为什么我会得到400代码响应。

你能帮我吗?

谢谢!

0 个答案:

没有答案