java - 如何在spring boot中测试文件上传?

标签 java spring rest testing junit

我已经实现了类似于 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);
  }

}

现在我正在尝试使用以下方法测试其余端点:

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);
  }
}

失败并返回 400 - 所需的请求部分"file"不存在

我错过了什么?

最佳答案

可能你需要改变
new MockMultipartFile("test.png", "test.png", "image/png", inputStream);

new MockMultipartFile("文件", "test.png", "image/png", inputStream); 因为上传的文件参数名称是'file'

关于java - 如何在spring boot中测试文件上传?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45565125/

相关文章:

java - 使用通配符泛型实现compareTo

java - RxAndroid : How to emit zipped observable every minute?

spring - 我应该如何在同一个 tomcat 上部署多个 webapps(使用相同的第三方 jar)以使用最小的 RAM

java - react excel 文件下载损坏

c# - 在 HttpClient 和 WebClient 之间做出决定

java - Guice 辅助注入(inject)多个构造函数总是调用默认构造函数

java - 是否可以使用java将文件写入远程目录?

java - Spring :找不到资源

node.js - 是否在 Mongoose 良好实践之上使用 Joi 进行验证?

spring - java.lang.NoSuchMethodError : org. springframework.data.jpa.repository.config.JpaRepositoryConfigExtension.registerIfNotAlreadyRegistered