Spring Boot Unit Test for Spring MVC Controller

Spring provides powerful features to make controller tests by creating request and receiving response without need of deploying code to a web container. This tutorial introduces Spring Boot Unit Test for Spring MVC Controller.

I. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.4.2.RELEASE

II. Overview
1. Goal

To build an REST web service and use Unit Test for Controller testing case without deploying code to a web container.

2. Project Structure

3. Step to do

– Create Spring Boot project & add Dependencies
– Create a DataModel class
– Create a Web Controller
– Create a UnitTest class
– Run Spring UnitTest & Enjoy Result

III. Practice
1. Create Spring Boot project & add Dependencies

– Open Spring Tool Suite, on Menu, choose File -> New -> Spring Starter Project, then fill each fields.

Click Next, in Web: choose Web:

Click Finish. Spring Boot project will be created successfully.

– Open pom.xml, necessary dependencies for Spring Boot Web MVC and Test are created automatically:

2. Create a DataModel class

Under package model, create class Customer:

3. Create a Web Controller

Under package controller, create class WebController.

After sending right request, we will receive a JSON like this:

The requirement is creating Unit Test for validating that JSON data.

4. Create a UnitTest class

Under src/test/java, create MyUnitTest class.

By default, Spring Boot automatically creates a class ProjectName_ApplicationTests (in our case, SpringUnitTestApplicationTests) that will load webApplicationContext, so we should extend it and @Autowire.

MockMvc is used to write service side test for spring MVC applications.

This example creates 2 test cases for validating request Status, content Type and customer Info using andExpect() method.

5. Run Spring UnitTest & Enjoy Result

– Config maven build:
clean install
– Run project with mode JUnit Test
– Check results in SpringJUnitTest[JUnit] Window:

IV. Source Code


Related Posts

Got Something To Say:

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