How to Write Unit Tests for File Upload APIs in Spring Boot
This guide shows backend developers how to write unit tests for file‑upload endpoints in Spring Boot using MockMvc, including a complete example with MockMultipartFile and emphasizing test‑driven design for better code quality.
In response to a question about how to write unit tests for file upload endpoints, the article explains why backend developers should master unit testing and demonstrates a practical example using Spring Boot and MockMvc.
First, a simple test for a regular GET endpoint is shown, highlighting the use of @SpringBootTest, MockMvc, and assertions on the response.
@SpringBootTest
public class Chapter11ApplicationTests {
private MockMvc mvc;
@Before
public void setUp() {
mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
}
@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello World")));
}
}For a file‑upload API the same MockMvc framework is used, but the request type changes to multipart and a MockMultipartFile is created to simulate the uploaded file.
@SpringBootTest(classes = Chapter43Application.class)
public class FileTest {
@Autowired
protected WebApplicationContext context;
protected MockMvc mvc;
@BeforeEach
public void setUp() {
mvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void uploadFile() throws Exception {
MockMultipartFile file = new MockMultipartFile(
"file",
"hello.txt",
MediaType.TEXT_PLAIN_VALUE,
"Hello, World!".getBytes()
);
MvcResult result = mvc.perform(
MockMvcRequestBuilders.multipart("/upload")
.file(file))
.andDo(print())
.andExpect(status().isOk())
.andReturn();
}
}The article emphasizes that the core testing logic remains the same; only the request type and payload differ. It encourages developers to consider testability when designing APIs and even adopt test‑driven development.
Code Example
Full examples are available in the GitHub repository at https://github.com/dyc87112/SpringBoot-Learning/ under the chapter4-3 directory.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
