Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Spring Boot MockMVC Example
Next article icon

Spring Boot MockMVC Example

Last Updated : 06 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Automated testing plays a vital role in the software industry. In this article, let us see how to do the testing using MockMvc for a Spring Boot project. To test the web layer, we need MockMvc and by using @AutoConfigureMockMvc, we can write tests that will get injected. SpringBootApplication is an excellent one that adds the following

  1. @Configuration
  2. @EnableAutoConfiguration
  3. @EnableWebMvc
  4. @ComponentScan

The application can ordinarily run as a Java application and hence development wise it is easier. Let's see the concept via a sample project

Example Project

Project Structure:

 

As it is a maven project, all dependencies are available under 

pom.xml

Dependencies like

  1. JDK 1.8
  2. Spring version from 2.2.5 onwards
  3. Maven 3.2+ and in the case of Gradle, it is Gradle 4+

We should add all the dependencies in pom.xml(in the case of the Maven project)

XML
<?xml version="1.0" encoding="UTF-8"?> <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.gfg.sample</groupId>     <artifactId>sampleboot-unit-testing-with-mock-mvc</artifactId>     <version>1.0-SNAPSHOT</version>      <parent>         <groupId>org.springframework.boot</groupId>         <artifactId>spring-boot-starter-parent</artifactId>         <!-- Mandatory -->         <version>2.2.5.RELEASE</version>     </parent>      <properties>         <java.version>1.8</java.version>     </properties>      <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>         </dependency>     </dependencies> </project> 

We are using MockMvc to test the web layer. That is we should have a model. a controller, and a view. Let us see the controller file

WelcomeMvcController.java

Each and every method should have either Getmapping or Postmapping

Java
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping;  @Controller public class WelcomeMvcController {     @Autowired     private WelcomeService welcomeService;          @GetMapping(value = "/")     public String greeting1(String name, Model model) {         model.addAttribute("welcome", welcomeService.greetingMessage1(name));         return "welcome-page";     }          @GetMapping(value = "/event")     public String greeting2(String name, Model model) {         model.addAttribute("welcomeToEvent", welcomeService.greetingMessage2(name));         return "event-page";     } } 

Required services are written in the service file

WelcomeService.java

Java
import org.springframework.stereotype.Service;  @Service public class WelcomeService {     public String greetingMessage1(String name) {         return String.format("Welcome , %s to the world of programming!!!", name );     }        public String greetingMessage2(String attendee) {         return String.format("Welldone , %s You are selected to the contest!!!", attendee );     } } 

SpringBoot Application is run as an ordinary Java application only

WebAppMain.java

Java
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;  @SpringBootApplication public class WebAppMain {     public static void main(String[] args) {         SpringApplication.run(WebAppMain.class, args);     } } 

Now let us start to write the test class that tests the web layer by using MockMvc

WelcomeWebAppTest.java

Java
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers;  @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class WelcomeWebAppTest {     @Autowired     private MockMvc mockMvc;      @Test     // We have to write out expectations and the        // expectations need to match with actuals       // When this is run, it imitates and accesses        // the web layer and get the output.     public void testWelcome() throws Exception {         this.mockMvc.perform(MockMvcRequestBuilders.get("/").param("name", "Geeks"))                 .andExpect(MockMvcResultMatchers.status().isOk())                 .andExpect(MockMvcResultMatchers.model().attribute("welcome",                         "Welcome , Geeks to the world of programming!!!"))                 .andExpect(MockMvcResultMatchers.view().name("welcome-page"))                 .andDo(MockMvcResultHandlers.print());     }      @Test     public void testWelcomeToEvent() throws Exception {         this.mockMvc.perform(MockMvcRequestBuilders.get("/event").param("name", "Geeks"))                 .andExpect(MockMvcResultMatchers.status().isOk())                 .andExpect(MockMvcResultMatchers.model().attribute("welcomeToEvent",                         "Welldone , Geeks You are selected to the contest!!!"))                 .andExpect(MockMvcResultMatchers.view().name("event-page"))                 .andDo(MockMvcResultHandlers.print());     }  } 

Once the project is complete and does not contain any errors, we can run the test file as an ordinary JUNIT application

 

Console Output:

Console Output
 
Console Output

Once we are getting response 200 means the service is available and the parameters are passed properly and it is producing a positive response. With that response, we are comparing the details by means of

Java
this.mockMvc.perform(MockMvcRequestBuilders.get("/").param("name", "Geeks"))                 .andExpect(MockMvcResultMatchers.status().isOk()) // checking status                 .andExpect(MockMvcResultMatchers.model().attribute("welcome",                         "Welcome , Geeks to the world of programming!!!")) // sent attribute and its value check                 .andExpect(MockMvcResultMatchers.view().name("welcome-page")) // its view name check                 .andDo(MockMvcResultHandlers.print()); 

Like this, we can test the web layer in the above-said ways

Conclusion

Automated testing helps to avoid tons of errors and error-free code and helps for good quality software. In the Spring Boot project, we can use MockMvc and can achieve the same.


Next Article
Spring Boot MockMVC Example

P

priyarajtt
Improve
Article Tags :
  • Java
  • Project
  • Software Testing
  • Java-Spring-Boot
Practice Tags :
  • Java

Similar Reads

    Spring Boot - Consume JSON Object From Kafka Topics
    Apache Kafka is a publish-subscribe messaging system. A messaging system lets someone is sending messages between processes, applications, and servers. Broadly Speaking, Apache Kafka is software where topics (A topic might be a category) can be defined and further processed. Applications may connect
    4 min read
    Spring Boot Kafka Producer Example
    Spring Boot is one of the most popular and most used frameworks of Java Programming Language. It is a microservice-based framework and to make a production-ready application using Spring Boot takes very less time. Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applica
    3 min read
    Spring Boot Kafka Consumer Example
    Spring Boot is one of the most popular and most used frameworks of Java Programming Language. It is a microservice-based framework and to make a production-ready application using Spring Boot takes very less time. Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applica
    3 min read
    Message Compression in Apache Kafka using Spring Boot
    Generally, producers send text-based data, such as JSON data. It is essential to apply compression to the producer in this situation. Producer messages are transmitted uncompressed by default. There are two types of Kafka compression. 1. Producer-Level Kafka Compression When compression is enabled o
    4 min read
    Spring Boot - Create and Configure Topics in Apache Kafka
    Topics are a special and essential component of Apache Kafka that are used to organize events or messages. In other words, Kafka Topics enable simple data transmission and reception across Kafka Servers by acting as Virtual Groups or Logs that store messages and events in a logical sequence. In this
    2 min read
    How to Test Spring Boot Project using ZeroCode?
    Zerocode automated testing framework for a REST API project concept is getting seen via this tutorial by taking a sample spring boot maven project. Let us see the dependencies for Zerocode : <dependency> <groupId>org.jsmart</groupId> <artifactId>zerocode-tdd</artifactId
    5 min read
    Validation in Spring Boot
    In this article, via a Gradle project, let us see how to validate a sample application and show the output in the browser. The application is prepared as of type Spring Boot and in this article let us see how to execute via the command line as well. Example Project Project Structure:   As this is th
    5 min read
    Spring Boot – Validation using Hibernate Validator
    Hibernate Validator provides a powerful and flexible way to validate data in Spring Boot applications. Validating user input is essential for building secure and reliable applications. Spring Boot makes this easy with Hibernate Validator, the reference implementation of JSR 380 (Bean Validation API)
    6 min read
    How to Connect MongoDB with Spring Boot?
    In recent times MongoDB has been the most used database in the software industry. It's easy to use and learn This database stands on top of document databases it provides the scalability and flexibility that you want with the querying and indexing that you need. In this, we will explain how we conne
    4 min read
    Spring Boot - File Handling
    Spring Boot is a popular, open-source spring-based framework used to develop robust web applications and microservices. As it is built on top of Spring Framework it not only has all the features of Spring but also includes certain special features such as auto-configuration, health checks, etc. whic
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences