|
| 1 | +import com.didispace.chapter43.Chapter43Application; |
| 2 | +import org.junit.jupiter.api.BeforeEach; |
1 | 3 | import org.junit.jupiter.api.Test; |
| 4 | +import org.springframework.beans.factory.annotation.Autowired; |
| 5 | +import org.springframework.boot.test.context.SpringBootTest; |
| 6 | +import org.springframework.http.MediaType; |
| 7 | +import org.springframework.mock.web.MockMultipartFile; |
| 8 | +import org.springframework.test.web.servlet.MockMvc; |
| 9 | +import org.springframework.test.web.servlet.MvcResult; |
| 10 | +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; |
| 11 | +import org.springframework.test.web.servlet.setup.MockMvcBuilders; |
| 12 | +import org.springframework.web.context.WebApplicationContext; |
2 | 13 |
|
| 14 | +import java.io.IOException; |
| 15 | + |
| 16 | +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; |
| 17 | +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; |
| 18 | + |
| 19 | + |
| 20 | +@SpringBootTest(classes = Chapter43Application.class) |
3 | 21 | public class FileTest { |
4 | 22 |
|
| 23 | + @Autowired |
| 24 | + protected WebApplicationContext context; |
| 25 | + protected MockMvc mvc; |
| 26 | + |
| 27 | + @BeforeEach |
| 28 | + public void setUp() { |
| 29 | + mvc = MockMvcBuilders.webAppContextSetup(context).build(); |
| 30 | + } |
| 31 | + |
5 | 32 | @Test |
6 | 33 | public void uploadFile() throws Exception { |
| 34 | + MockMultipartFile file = mockFile(); |
| 35 | + |
| 36 | + final MvcResult result = mvc.perform( |
| 37 | + MockMvcRequestBuilders |
| 38 | + .multipart("/upload") |
| 39 | + .file(file)) |
| 40 | + .andDo(print()) |
| 41 | + .andExpect(status().isCreated()) |
| 42 | + .andReturn(); |
| 43 | + } |
7 | 44 |
|
| 45 | + private MockMultipartFile mockFile() throws IOException { |
| 46 | + MockMultipartFile file = new MockMultipartFile( |
| 47 | + "file", |
| 48 | + "hello.txt", |
| 49 | + MediaType.TEXT_PLAIN_VALUE, |
| 50 | + "Hello, World!".getBytes() |
| 51 | + ); |
8 | 52 |
|
| 53 | + return file; |
9 | 54 | } |
10 | 55 |
|
11 | 56 | } |
0 commit comments