Introduction
Here in this tutorial we will see examples on Junit testing of file upload and download in Spring REST Controllers. We have seen how to write Junit test cases on Spring REST Controllers in my previous tutorial but I did not show how to write Junit testing of file upload and download in Spring REST Controllers but here we will see those in action.
We will use one of the most widely used and popular JUnit Testing Mocking framework – Mockito to write our test cases in this example as well. But before going forward please read tutorial File Upload example using Spring REST Controller and File Download example using REST Controller.
You may also check my other Junit Tutorials.
Let’s move on to the example…
Prerequisites
Knowledge of Junit, Java
File Upload example using Spring REST Controller
File Download example using REST Controller
Example with Source Code
We use Spring framework’s MultipartFile to upload a file and when we download a file we send byte[] as a response OutputStream so that file will be forcefully downloaded and user will be given option for saving the downloaded file.
Here we will not create two separate Junit test classes and we will accomodate two separate functions in one Junit class for Junit testing of file upload and download in Spring REST Controllers.
Setting up a gradle project
In your existing gradle based Java project in Eclipse add the below dependencies for Junit in build.gradle script:
testImplementation("junit:junit")
testImplementation("org.springframework.boot:spring-boot-starter-test")
Building the project
Build the project by executing command gradle clean build and it should download all the required Junit jar files in classpath of the project.
Creating Junit class
Now in src/test/java directory under the package com.roytuts.controller, create below Junit test class
We run the test class with MockitoJUnitRunner
class. We mock the external service and inject into test class. We only create actual object for the class for which we are going to check the functionality through Junit test cases.
We inject all other mock services into this class object using @InjectMocks
annotation. We perform all initialization tasks in init()
method and this method must be annotated with @Before
in order to execute any test case.
Next we put annotations for all the test methods and run the test case for each functionality of the controller method.
Notice how we have mocked the MultipartFile
object and test the upload functionality and check the final response. We also test the file download functionality and check the response.
package com.roytuts.controller;
@RunWith(MockitoJUnitRunner.class)
public class FileUploadDownloadRestControllerTest {
private InputStream is;
private MockMvc mockMvc;
@Mock
private EmployeeService employeeService;
@Spy
@InjectMocks
private FileUploadDownloadRestController controller = new FileUploadDownloadRestController();
@Before
public void init() {
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
is = controller.getClass().getClassLoader().getResourceAsStream("excel.xlsx");
}
@Test
public void testUploadFile() throws Exception {
MockMultipartFile mockMultipartFile = new MockMultipartFile("file", "excel.xlsx", "multipart/form-data", is);
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.multipart("/upload").file(mockMultipartFile).contentType(MediaType.MULTIPART_FORM_DATA))
.andExpect(MockMvcResultMatchers.status().is(200)).andReturn();
Assert.assertEquals(200, result.getResponse().getStatus());
Assert.assertNotNull(result.getResponse().getContentAsString());
Assert.assertEquals("excel.xlsx", result.getResponse().getContentAsString());
}
@Test
public void testDownloadFile() throws Exception {
Mockito.when(employeeService.getEmployees()).thenReturn(new ArrayList<>());
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/download").contentType(MediaType.APPLICATION_OCTET_STREAM)).andExpect(MockMvcResultMatchers.status().is(200)).andReturn();
Assert.assertEquals(200, result.getResponse().getStatus());
Assert.assertEquals(2, result.getResponse().getContentAsByteArray().length);
Assert.assertEquals("text/json", result.getResponse().getContentType());
}
}
Testing Test Cases
Now run the above Junit test class and you should see the success results for test cases.
Thanks for reading.
Thank you it worked for me.
Thank you so much, you saved me!