Junit Testing for Multiple Files Upload Spring REST Controller

Introduction

Here I am going to write Junit test case for testing multiple files upload in Spring REST Controller. I have already created how to upload multiple files using Spring REST API and I also had shown how to test it through REST client tool – Postman. In this tutorial I am going to use Junit 5, @WebMvcTest annotation to test the multiple files upload REST API.

@WebMvcTest annotation can be used not only to test Spring Controllers but also Spring REST Controllers. I will build the applications using both maven and gradle tools. In my previous example I have shown how to write Junit test cases for Spring REST controllers that upload and download single file.

@WebMvcTest annotation is used for unit testing of Spring MVC Applications in situation where the test objective is to just focus on Spring MVC Components.

Prerequisites

Eclipse 2020-06, At least Java 8, Gradle 6.5.1, Maven 3.6.3, Spring Boot 2.3.2, Junit 5

How to upload multiple files using Spring REST API

How to include required project into another gradle project

Project Setup

You can create either gradle or maven based project in Eclipse. The name of the project is junit-spring-rest-api-multiple-files-upload.

If you are creating gradle based project then you can update project’s build.gradle file as shown below:

plugins {
    id 'java-library'
}

sourceCompatibility = 12
targetCompatibility = 12

repositories {
    mavenCentral()
}

dependencies {
	implementation project(":spring-rest-multiple-files-upload")
	testImplementation 'org.junit.jupiter:junit-jupiter-params:5.6.2'
    testImplementation("org.springframework.boot:spring-boot-starter-test:2.3.2.RELEASE") {
    	exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

Notice in the above project I have included the dependent project spring-rest-multiple-files-upload into the current project junit-spring-rest-api-multiple-files-upload.

If you are creating maven based project then you can use below pom.xml file:

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.roytuts</groupId>
	<artifactId>junit-spring-rest-api-multiple-files-upload</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>com.roytuts</groupId>
			<artifactId>spring-rest-multiple-files-upload</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<version>2.3.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-params</artifactId>
			<version>5.6.2</version>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

    <build>
        <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>at least 8</source>
					<target>at least 8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Junit Test for REST API – Multiple Files Upload

Now I am going to create Junit test class to test controller and REST controller by applying the @WebMvcTest annotation.

In the below class I have used @WebMvcTest annotation along with the REST controller class which I want to test.

I have mocked the MVC using MockMvc class to test the REST controller’s endpoint.

As I am going to test multiple files, so I have to upload multiple files. I am uploading total three files. Two file are kept under classpath test resources and one I have hardcoded with string data value.

I have defined three separate MockMultipartFile to upload three files. So as many files as you want to upload you need to define the same number of MockMultipartFile.

Notice I have also passed original name and content type for each file while creating MockMultipartFile object. You can also use another constructor that takes only file name (request body parameter name) and InputStream (the full file path) but in the output you will get null for original file name and content type.

Then sending each MockMultipartFile object in the file() method and finally I check the status is OK (200) or not from the response.

package com.roytuts.spring.rest.multiple.files.upload.rest.controller.test;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import com.roytuts.spring.rest.multiple.files.upload.rest.controller.MultipleFileUploadRestController;

@WebMvcTest(MultipleFileUploadRestController.class)
public class MultipleFileUploadRestControllerTest {

	@Autowired
	private MockMvc mockMvc;

	@Test
	public void testMultipleFilesUploadRestController() throws Exception {
		MockMultipartFile file1 = new MockMultipartFile("multipleFiles", "sql-changelog-alter-table.sql",
				"application/sql", this.getClass().getResourceAsStream("/sql-changelog-alter-table.sql"));

		MockMultipartFile file2 = new MockMultipartFile("multipleFiles", "WishNet.txt", "text/plain",
				this.getClass().getResourceAsStream("/WishNet.txt"));

		MockMultipartFile file3 = new MockMultipartFile("multipleFiles", "Static Data", "text/plain",
				"test data".getBytes());

		mockMvc.perform(MockMvcRequestBuilders.multipart("/upload/multiple/files").file(file1).file(file2).file(file3))
				.andExpect(MockMvcResultMatchers.status().isOk());
	}

}

Testing the Application

Executing the above Junit test class will give you the following output with success message as shown:

junit testing for multiple files upload in spring rest controller

The console output is given below:

f.u.r.c.MultipleFileUploadRestController : InputStream: java.io.ByteArrayInputStream@6ef60295
f.u.r.c.MultipleFileUploadRestController : OriginalName: sql-changelog-alter-table.sql
f.u.r.c.MultipleFileUploadRestController : Name: multipleFiles
f.u.r.c.MultipleFileUploadRestController : ContentType: application/sql
f.u.r.c.MultipleFileUploadRestController : Size: 4318
f.u.r.c.MultipleFileUploadRestController : InputStream: java.io.ByteArrayInputStream@3127cb44
f.u.r.c.MultipleFileUploadRestController : OriginalName: WishNet.txt
f.u.r.c.MultipleFileUploadRestController : Name: multipleFiles
f.u.r.c.MultipleFileUploadRestController : ContentType: text/plain
f.u.r.c.MultipleFileUploadRestController : Size: 33
f.u.r.c.MultipleFileUploadRestController : InputStream: java.io.ByteArrayInputStream@3234474
f.u.r.c.MultipleFileUploadRestController : OriginalName: Static Data
f.u.r.c.MultipleFileUploadRestController : Name: multipleFiles
f.u.r.c.MultipleFileUploadRestController : ContentType: text/plain
f.u.r.c.MultipleFileUploadRestController : Size: 9

Source Code

Download

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *