This example, shows how to use MockMvcRequestBuilders.multipart() .
Note that, starting Spring 5.0, MockMvcRequestBuilders.fileUpload() has been deprecated in favor of MockMvcRequestBuilders.multipart() method.
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyWebConfig.class)
public class UploadControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
}
@Test
public void testController() throws Exception {
ResultMatcher ok = MockMvcResultMatchers.status().isOk();
String fileName = "test.txt";
File file = new File(FileUploadController.targetFolder + fileName);
//delete if exits
file.delete();
MockMultipartFile mockMultipartFile = new MockMultipartFile("user-file",fileName,
"text/plain", "test data".getBytes());
MockHttpServletRequestBuilder builder =
MockMvcRequestBuilders.multipart("/upload")
.file(mockMultipartFile);
this.mockMvc.perform(builder).andExpect(ok)
.andDo(MockMvcResultHandlers.print());;
Assert.assertTrue(file.exists());
}
} mvn test -q Outputd:\example-projects\spring-mvc\file-upload\spring-mock-mvc-request-builders-multipart>mvn test -q
------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.logicbig.example.UploadControllerTest
MockHttpServletRequest: HTTP Method = POST Request URI = /upload Parameters = {} Headers = {Content-Type=[multipart/form-data]} Body = <no character encoding set> Session Attrs = {}
Handler: Type = com.logicbig.example.FileUploadController Method = public java.lang.String com.logicbig.example.FileUploadController.handlePostRequest(org.springframework.web.multipart.MultipartHttpServletRequest,org.springframework.ui.Model) throws java.io.IOException
Async: Async started = false Async result = null
Resolved Exception: Type = null
ModelAndView: View name = null View = null Model = null
FlashMap: Attributes = null
MockHttpServletResponse: Status = 200 Error message = null Headers = {Content-Type=[text/plain;charset=ISO-8859-1], Content-Length=[18]} Content type = text/plain;charset=ISO-8859-1 Body = test response body Forwarded URL = null Redirected URL = null Cookies = [] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.949 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
Example ProjectDependencies and Technologies Used: - spring-webmvc 5.0.3.RELEASE: Spring Web MVC.
- spring-test 5.0.3.RELEASE: Spring TestContext Framework.
- javax.servlet-api 3.0.1 Java Servlet API
- junit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
- commons-fileupload 1.3.1:
The Apache Commons FileUpload component provides a simple yet flexible means of adding support for multipart
file upload functionality to servlets and web applications.
- JDK 1.8
- Maven 3.3.9
|
|