2017-08-08 86 views
1

我已實施類似於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

你能提供有關如何設置測試更多的細節? – Plog

+0

@Plog,我添加了測試設置。謝謝你的提醒。 –

回答

3

也許你需要改變
new MockMultipartFile("test.png", "test.png", "image/png", inputStream);

new MockMultipartFile("file", "test.png", "image/png", inputStream); 爲上傳文件的參數名稱「文件」

+0

是的,這應該可以解決它,我正準備發佈相同的內容。 – Plog

+0

謝謝,這真的解決了這個問題。 –