我实施了类似于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 - Required request part 'file' is not present
失败。
我错过了什么?
答案 0 :(得分:5)
可能你需要改变
new MockMultipartFile("test.png", "test.png", "image/png", inputStream);
到
new MockMultipartFile("file", "test.png", "image/png", inputStream);
因为上传的文件参数名称是'file'