CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > How to > How to write Unit Test for Controller layer in Spring Boot?

Java Tutorial Menu

  • Introduction
    • What is Java
    • History Of Java
    • Install Java
    • What is JVM
    • JDK vs JRE vs JVM
    • Java Bytecode
    • OOP vs POP
    • Compile and Run Java
  • Tokens, Expressions and Control Structures
    • Primitive data types
    • Integers
    • Floating Points
    • Characters
    • Booleans
    • User Defined Data Type
    • Declarations
    • Constants
    • Identifiers
    • Literals
    • Type Conversion and Casting
    • Variables
    • Default Variable Initialization
    • Command Line Arguments
    • Arrays of Primitive Types
    • Comment Syntax
    • Garbage Collection
    • Expressions
    • Operators
    • Arithmetic Operator
    • Bitwise and Shift Operator
    • Comparison or Relational Operators
    • Logical Operators
    • Assignment Operators
    • Ternary Operator
    • Increment and Decrement Operator
    • Control Statements
  • OOP Concepts
    • Class and Object
    • Create Class Instance
    • Method
    • Abstraction
    • Encapsulation
    • this keyword
    • Constructor
    • Pass by Value
    • Access Modifier/Control
    • Polymorphism
    • Method Overloading vs Method Overriding
    • Recursion
    • Nested and Inner Class
  • Inheritance and Packaging
    • Inheritance
    • extends Keyword
    • super Keyword
    • Object Class
    • Abstract class
    • Final Class
    • Java Package
    • Interface
  • Handling Error/ Exceptions
    • What is Exception
    • Exception Handling Keywords
    • Common Java Errors
    • User Defined Exception
    • Throwing and re-throwing Exception
    • finally Block
  • Strings
    • Java String Tutorial
  • Threads
    • Introduction
    • Create Thread
    • Thread Lifecycle
    • Thread Priority
    • Thread Synchronization
    • Inner Thread Communication
    • Thread Deadlock
  • IO and Streams
    • java.io Package
    • Files and Directories
    • Byte Stream
    • Character Stream
    • Console Input and Output
    • Serializable and Deserializable
  • Core Packages
    • java.lang Package
    • Math
    • Wrapper Classes
    • java.lang.Number
    • Double
    • Float
    • Integers
    • java.lang.Byte
    • java.lang.Short
    • java.lang.Long
    • java.lang.Character
    • java.lang.Boolean
    • java.util package
    • Vector Class
    • Stack Class
    • Dictionary Class
    • Hashtable
    • Enumeration or Enum
    • Generate Random Number
  • Holding Collection of Data
    • Arrays
    • Map
    • List
    • Set
    • Collection Interface
    • Collections Class
    • ArrayList
    • HashSet
    • TreeSet
    • Comparator
  • Java Bean
    • What is Java Bean
    • Advantages and Disadvantages of Java Bean
    • Java Beans API
    • Introspection
    • Java Bean Properties
    • Bound and Constrained Properties
    • BeanInfo Interface
    • Customizers
    • Java Beans Persistence
    • BeanDescriptor

How to write Unit Test for Controller layer in Spring Boot?

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Published: January 7, 2022 ยท 4 min read ยท 0 Comments
Share: X in ๐Ÿ”—
git change remote url

In this post, we will learn to write a Unit Test for the Controller layer of our spring boot application. We will be using the following version of our Spring Boot and Java.

  • Spring Boot: 2.6.2
  • JDK 11

Table of Contents

Prerequisite
Dependencies
LoginController
LoginRequest bean
LoginService
Create a Test case for our LoginController
Conclusion

Prerequisite

  • You must know how to create a Spring boot application and open it in your favorite IDE like Eclipse.

Dependencies

In this example, we need the following dependencies. Make sure that these dependencies are available in your pom.xml file.

<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>
<dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Note

Most of the time, the spring-boot-starter-test dependency will be added automatically when you add spring-boot-starter-web.
  • The spring-boot-starter-web dependency is used for building the web application, including RESTful applications using Spring MVC. It uses Tomcat as the default embedded container.
  • The spring-boot-starter-test dependency contains all the required dependencies to run our test. This is the magic of using Spring Boot :).
  • The lombok dependency is a Java annotation library which helps us to reduce boilerplate code in our classes.
  • The spring-boot-starter-validation dependency is uses to validate oru Beans.

LoginController

package com.codersathi.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.codersathi.bean.LoginRequest;
import com.codersathi.service.LoginService;

@RestController
@RequestMapping("/login")
public class LoginController {

	@Autowired
	private LoginService service;
	
	
	@PostMapping
        @ResponseStatus(code = HttpStatus.OK)
	public String login(@Validated @RequestBody LoginRequest request) {
		return service.login(request);
	}
}

LoginRequest bean

package com.codersathi.bean;

import javax.validation.constraints.NotBlank;

import lombok.Data;

@Data
public class LoginRequest {
	@NotBlank(message = "username is required")
	private String username;
	@NotBlank(message = "password is required")
	private String password;
}

LoginService

package com.codersathi.service;

import org.springframework.stereotype.Service;

import com.codersathi.bean.LoginRequest;

@Service
public class LoginService {
	public String login(LoginRequest loginRequest) {
		return "We don't care it while testing our controller";
	}
}

Now, we have created our login endpoint, and when the user sends the username and password in POST request it will return the Success message as a response.

In our example, we have also added a bean validation so that, if the user tries to send a request without providing the username and password in the request body it will throw an exception saying these values are required.

So, let’s test our controller to make sure that our API endpoint validates the request and sends the success message regardless of the response from LoginService.

Since we are trying to write a Unit test for our LoginController we will be mocking the LoginService and expect a successful response.

Create a Test case for our LoginController

package com.codersathi;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

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.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;

import com.codersathi.bean.LoginRequest;
import com.codersathi.controller.LoginController;
import com.codersathi.service.LoginService;
import com.fasterxml.jackson.databind.ObjectMapper;

@WebMvcTest(LoginController.class)
class LoginControllerTest {

	@Autowired
	private MockMvc mockMvc;

	@MockBean
	private LoginService loginService;

	@Test	
	void test_login() throws Exception {
		LoginRequest request = new LoginRequest();
		request.setUsername("myusername");
		request.setPassword("mypassword");

		when(loginService.login(request)).thenReturn("Success");

		mockMvc.perform(post("/login").contentType(MediaType.APPLICATION_JSON)
				.content(new ObjectMapper().writeValueAsString(request))).andExpect(status().isOk()).andReturn();

	}

}

Now, when we execute then our test should pass.

Conclusion

In this post, we learned to write unit test the Controller layer of the Spring Boot application

Related Posts:

  • Integrate Spring AI with DeepSeek AI
  • Install and Set Up Java Development Environment
  • Spring Data REST example.
  • Step-by-Step Guide to Set Up Eclipse with Tomcat…
  • Difference Between JDK JRE and JVM
  • Unit Testing and Integration Testing
Tags:javaspring-bootunit-testing
Was this article helpful?
โ† Previous ArticleJava: The Go-To Programming Language for Developers Everywhere
Next Article โ†’Create Spring Boot project using Spring Initialzer

Leave a Comment Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
  • Complete Guide to JaCoCo: How to Measure Java Code Coverage Accurately
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
ยฉ 2026 CoderSathi. All rights reserved. Privacy Policy ยท Sitemap