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.

Related posts:
UnitTest – Maven skip test with SpringBoot
@DataJPATest with Spring Boot
How to use Spring JPA MySQL | Spring Boot

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:
springaop-aspectj-configweb

Click Finish. Spring Boot project will be created successfully.

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

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
</dependencies>

2. Create a DataModel class

Under package model, create class Customer:


package com.javasampleapproach.unittest.model;

public class Customer {

	private String name;
	private String location;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	@Override
	public String toString() {
		return "Customer [name=" + name + ", location=" + location + "]";
	}

}

3. Create a Web Controller

Under package controller, create class WebController.


package com.javasampleapproach.unittest.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.javasampleapproach.unittest.model.Customer;

@RestController
public class WebController {

	@RequestMapping(value = "/customer", method = RequestMethod.GET)
	public Customer getAddress() {

		Customer customer = new Customer();
		customer.setName("Jack");
		customer.setLocation("US");

		return customer;
	}
}

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


{"name":"Jack","location":"US"}

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

4. Create a UnitTest class

Under src/test/java, create MyUnitTest class.


package com.javasampleapproach.unittest;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

public class MyUnitTest extends SpringUnitTestApplicationTests {

	@Autowired
	private WebApplicationContext webApplicationContext;

	private MockMvc mockMvc;

	@Before
	public void setup() {
		mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
	}

	@Test
	public void validate_customerInfo1() throws Exception {
		mockMvc.perform(get("/customer")).andExpect(status().isOk())
				.andExpect(content().contentType("application/json;charset=UTF-8"))
				.andExpect(jsonPath("$.name").value("John")).andExpect(jsonPath("$.location").value("US"));

	}

	@Test
	public void validate_customerInfo2() throws Exception {
		mockMvc.perform(get("/customer")).andExpect(status().isOk())
				.andExpect(content().contentType("application/json;charset=UTF-8"))
				.andExpect(jsonPath("$.name").value("Jack")).andExpect(jsonPath("$.location").value("US"));

	}
}

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

SpringUnitTest



By grokonez | December 22, 2016.

Last updated on April 22, 2021.



Related Posts


Got Something To Say:

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

*