我已實施類似於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
。
我錯過了什麼?
你能提供有關如何設置測試更多的細節? – Plog
@Plog,我添加了測試設置。謝謝你的提醒。 –