简体   繁体   中英

How to test file upload in spring boot?

I have implemented a rest service similar to this one .

UserController.java

@RestController
@RequestMapping(path = "/user")
public class UserController {

  private final UserService userService;

  @Autowired
  public UserController(UserService userService) {
    this.userService = userService;
  }

  @PostMapping(path = "/{id}/avatar")
  public void handleUpload(@PathVariable("id") int id, @RequestParam("file") MultipartFile file) {
    if (file == null) {
        throw new DashboardException("Please select a valid picture");
    }
    userService.setAvatar(id, file);
  }

}

Now I am trying to test the rest endpoint with:

UserControllerEndpointTest.java

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class UserControllerEndpointTest {

  private static final int userId = 42;
  private static final String urlPath = String.format("/user/%d/avatar", userId);

  private MockMvc mockMvc;

  @Autowired
  private WebApplicationContext webApplicationContext;
  @Autowired
  private UserController controller;
  private UserService service;

  @Before
  public void setUp() throws NoSuchFieldException, IllegalAccessException {
    mockMvc = webAppContextSetup(webApplicationContext).build();
    service = Mockito.mock(UserService.class);
    injectField(controller, "userService", service);
  }

  @Test
  public void successfullySetAvatar() throws Exception {
    final InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("test.png");
    final MockMultipartFile avatar = new MockMultipartFile("test.png", "test.png", "image/png", inputStream);

    doNothing().when(service).setAvatar(userId, avatar);

    final MvcResult result = mockMvc.perform(fileUpload(urlPath).file(avatar))
            .andExpect(status().isOk())
            .andReturn();

    verify(service).setAvatar(userId, avatar);
  }
}

This fails with 400 - Required request part 'file' is not present .

What am I missing?

Probably you need to change
new MockMultipartFile("test.png", "test.png", "image/png", inputStream);
to
new MockMultipartFile("file", "test.png", "image/png", inputStream); as the uploaded file parameter name is 'file'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM